repo
stringclasses
900 values
file
stringclasses
754 values
content
stringlengths
4
215k
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 1.896 # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = high - strike_price european_call_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=c_approx, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective num_qubits = european_call_objective.num_qubits european_call = QuantumCircuit(num_qubits) european_call.append(uncertainty_model, range(num_uncertainty_qubits)) european_call.append(european_call_objective, range(num_qubits)) # draw the circuit european_call.draw() # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.maximum(0, x - strike_price) 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) european_call.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_call, objective_qubits=[3], post_processing=european_call_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallPricing european_call_pricing = EuropeanCallPricing( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=(low, high), uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (european_call_pricing.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) from qiskit_finance.applications.estimation import EuropeanCallDelta european_call_delta = EuropeanCallDelta( num_state_qubits=num_uncertainty_qubits, strike_price=strike_price, bounds=(low, high), uncertainty_model=uncertainty_model, ) european_call_delta._objective.decompose().draw() european_call_delta_circ = QuantumCircuit(european_call_delta._objective.num_qubits) european_call_delta_circ.append(uncertainty_model, range(num_uncertainty_qubits)) european_call_delta_circ.append( european_call_delta._objective, range(european_call_delta._objective.num_qubits) ) european_call_delta_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_delta.to_estimation_problem() # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval_processed) print("Exact delta: \t%.4f" % exact_delta) print("Esimated value: \t%.4f" % european_call_delta.interpret(result_delta)) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 A operator for QAE for the payoff function by # composing the uncertainty model and the objective uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # 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 rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [-1, 0] offsets = [strike_price - low, 0] f_min = 0 f_max = strike_price - low european_put_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective european_put = european_put_objective.compose(uncertainty_model, front=True) # 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) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put, objective_qubits=[num_uncertainty_qubits], post_processing=european_put_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price] slopes = [0, 0] offsets = [1, 0] f_min = 0 f_max = 1 european_put_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # construct circuit for payoff function european_put_delta = european_put_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=european_put_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) 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
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # 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 for uncertainty model uncertainty_model = LogNormalDistribution( num_uncertainty_qubits, mu=mu, sigma=sigma**2, bounds=(low, 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() # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 1.438 strike_price_2 = 2.584 # set the approximation scaling for the payoff function rescaling_factor = 0.25 # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, strike_price_2 - strike_price_1] f_min = 0 f_max = strike_price_2 - strike_price_1 bull_spread_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, rescaling_factor=rescaling_factor, ) # construct A operator for QAE for the payoff function by # composing the uncertainty model and the objective bull_spread = bull_spread_objective.compose(uncertainty_model, front=True) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = uncertainty_model.values y = np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) 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[np.logical_and(x >= strike_price_1, x <= strike_price_2)] ) print("exact expected value:\t%.4f" % exact_value) print("exact delta value: \t%.4f" % exact_delta) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread, objective_qubits=[num_uncertainty_qubits], post_processing=bull_spread_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # setup piecewise linear objective fcuntion breakpoints = [low, strike_price_1, strike_price_2] slopes = [0, 0, 0] offsets = [0, 1, 0] f_min = 0 f_max = 1 bull_spread_delta_objective = LinearAmplitudeFunction( num_uncertainty_qubits, slopes, offsets, domain=(low, high), image=(f_min, f_max), breakpoints=breakpoints, ) # no approximation necessary, hence no rescaling factor # construct the A operator by stacking the uncertainty model and payoff function together bull_spread_delta = bull_spread_delta_objective.compose(uncertainty_model, front=True) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=bull_spread_delta, objective_qubits=[num_uncertainty_qubits] ) # construct amplitude estimation ae_delta = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_delta = ae_delta.estimate(problem) conf_int = np.array(result_delta.confidence_interval) print("Exact delta: \t%.4f" % exact_delta) print("Estimated value:\t%.4f" % result_delta.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit.circuit.library import WeightedAdder, LinearAmplitudeFunction from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=list(zip(low, high))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_T^1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_T^2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 3.5 # map strike price from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price = ( (strike_price - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price] slopes = [0, 1] offsets = [0, 0] f_min = 0 f_max = 2 * (2**num_uncertainty_qubits - 1) - mapped_strike_price basket_objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar = AncillaRegister(max(n_aux, basket_objective.num_ancillas), "work") # additional qubits objective_index = u.num_qubits basket_option = QuantumCircuit(qr_state, qr_obj, ar_sum, ar) basket_option.append(u, qr_state) basket_option.append(agg, qr_state[:] + ar_sum[:] + ar[:n_aux]) basket_option.append(basket_objective, ar_sum[:] + qr_obj[:] + ar[: basket_objective.num_ancillas]) print(basket_option.draw()) print("objective qubit index", objective_index) # plot exact payoff function (evaluated on the grid of the uncertainty model) x = np.linspace(sum(low), sum(high)) y = np.maximum(0, x - strike_price) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function", size=15) plt.xlabel("Sum of Spot Prices ($S_T^1 + S_T^2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) exact_value = np.dot( u.probabilities[sum_values >= strike_price], sum_values[sum_values >= strike_price] - strike_price, ) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = basket_option.num_qubits - basket_option.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(basket_option, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) basket_option_measure = basket_option.measure_all(inplace=False) sampler = Sampler() job = sampler.run(basket_option_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = ( basket_objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=basket_option, objective_qubits=[objective_index], post_processing=basket_objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value: \t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt from scipy.interpolate import griddata %matplotlib inline import numpy as np from qiskit import QuantumRegister, QuantumCircuit, AncillaRegister, transpile from qiskit.circuit.library import IntegerComparator, WeightedAdder, LinearAmplitudeFunction from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import LogNormalDistribution # number of qubits per dimension to represent the uncertainty num_uncertainty_qubits = 2 # 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 # map to higher dimensional distribution # for simplicity assuming dimensions are independent and identically distributed) dimension = 2 num_qubits = [num_uncertainty_qubits] * dimension low = low * np.ones(dimension) high = high * np.ones(dimension) mu = mu * np.ones(dimension) cov = sigma**2 * np.eye(dimension) # construct circuit u = LogNormalDistribution(num_qubits=num_qubits, mu=mu, sigma=cov, bounds=(list(zip(low, high)))) # plot PDF of uncertainty model x = [v[0] for v in u.values] y = [v[1] for v in u.values] z = u.probabilities # z = map(float, z) # z = list(map(float, z)) resolution = np.array([2**n for n in num_qubits]) * 1j grid_x, grid_y = np.mgrid[min(x) : max(x) : resolution[0], min(y) : max(y) : resolution[1]] grid_z = griddata((x, y), z, (grid_x, grid_y)) plt.figure(figsize=(10, 8)) ax = plt.axes(projection="3d") ax.plot_surface(grid_x, grid_y, grid_z, cmap=plt.cm.Spectral) ax.set_xlabel("Spot Price $S_1$ (\$)", size=15) ax.set_ylabel("Spot Price $S_2$ (\$)", size=15) ax.set_zlabel("Probability (\%)", size=15) plt.show() # determine number of qubits required to represent total loss weights = [] for n in num_qubits: for i in range(n): weights += [2**i] # create aggregation circuit agg = WeightedAdder(sum(num_qubits), weights) n_s = agg.num_sum_qubits n_aux = agg.num_qubits - n_s - agg.num_state_qubits # number of additional qubits # set the strike price (should be within the low and the high value of the uncertainty) strike_price_1 = 3 strike_price_2 = 4 # set the barrier threshold barrier = 2.5 # map strike prices and barrier threshold from [low, high] to {0, ..., 2^n-1} max_value = 2**n_s - 1 low_ = low[0] high_ = high[0] mapped_strike_price_1 = ( (strike_price_1 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_strike_price_2 = ( (strike_price_2 - dimension * low_) / (high_ - low_) * (2**num_uncertainty_qubits - 1) ) mapped_barrier = (barrier - low) / (high - low) * (2**num_uncertainty_qubits - 1) # condition and condition result conditions = [] barrier_thresholds = [2] * dimension n_aux_conditions = 0 for i in range(dimension): # target dimension of random distribution and corresponding condition (which is required to be True) comparator = IntegerComparator(num_qubits[i], mapped_barrier[i] + 1, geq=False) n_aux_conditions = max(n_aux_conditions, comparator.num_ancillas) conditions += [comparator] # set the approximation scaling for the payoff function c_approx = 0.25 # setup piecewise linear objective fcuntion breakpoints = [0, mapped_strike_price_1, mapped_strike_price_2] slopes = [0, 1, 0] offsets = [0, 0, mapped_strike_price_2 - mapped_strike_price_1] f_min = 0 f_max = mapped_strike_price_2 - mapped_strike_price_1 objective = LinearAmplitudeFunction( n_s, slopes, offsets, domain=(0, max_value), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define overall multivariate problem qr_state = QuantumRegister(u.num_qubits, "state") # to load the probability distribution qr_obj = QuantumRegister(1, "obj") # to encode the function values ar_sum = AncillaRegister(n_s, "sum") # number of qubits used to encode the sum ar_cond = AncillaRegister(len(conditions) + 1, "conditions") ar = AncillaRegister( max(n_aux, n_aux_conditions, objective.num_ancillas), "work" ) # additional qubits objective_index = u.num_qubits # define the circuit asian_barrier_spread = QuantumCircuit(qr_state, qr_obj, ar_cond, ar_sum, ar) # load the probability distribution asian_barrier_spread.append(u, qr_state) # apply the conditions for i, cond in enumerate(conditions): state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append(cond, state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas]) # aggregate the conditions on a single qubit asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) # apply the aggregation function controlled on the condition asian_barrier_spread.append(agg.control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux]) # apply the payoff function asian_barrier_spread.append(objective, ar_sum[:] + qr_obj[:] + ar[: objective.num_ancillas]) # uncompute the aggregation asian_barrier_spread.append( agg.inverse().control(), [ar_cond[-1]] + qr_state[:] + ar_sum[:] + ar[:n_aux] ) # uncompute the conditions asian_barrier_spread.mcx(ar_cond[:-1], ar_cond[-1]) for j, cond in enumerate(reversed(conditions)): i = len(conditions) - j - 1 state_qubits = qr_state[(num_uncertainty_qubits * i) : (num_uncertainty_qubits * (i + 1))] asian_barrier_spread.append( cond.inverse(), state_qubits + [ar_cond[i]] + ar[: cond.num_ancillas] ) print(asian_barrier_spread.draw()) print("objective qubit index", objective_index) # plot exact payoff function plt.figure(figsize=(7, 5)) x = np.linspace(sum(low), sum(high)) y = (x <= 5) * np.minimum(np.maximum(0, x - strike_price_1), strike_price_2 - strike_price_1) plt.plot(x, y, "r-") plt.grid() plt.title("Payoff Function (for $S_1 = S_2$)", size=15) plt.xlabel("Sum of Spot Prices ($S_1 + S_2)$", size=15) plt.ylabel("Payoff", size=15) plt.xticks(size=15, rotation=90) plt.yticks(size=15) plt.show() # plot contour of payoff function with respect to both time steps, including barrier plt.figure(figsize=(7, 5)) z = np.zeros((17, 17)) x = np.linspace(low[0], high[0], 17) y = np.linspace(low[1], high[1], 17) for i, x_ in enumerate(x): for j, y_ in enumerate(y): z[i, j] = np.minimum( np.maximum(0, x_ + y_ - strike_price_1), strike_price_2 - strike_price_1 ) if x_ > barrier or y_ > barrier: z[i, j] = 0 plt.title("Payoff Function", size=15) plt.contourf(x, y, z) plt.colorbar() plt.xlabel("Spot Price $S_1$", size=15) plt.ylabel("Spot Price $S_2$", size=15) plt.xticks(size=15) plt.yticks(size=15) plt.show() # evaluate exact expected value sum_values = np.sum(u.values, axis=1) payoff = np.minimum(np.maximum(sum_values - strike_price_1, 0), strike_price_2 - strike_price_1) leq_barrier = [np.max(v) <= barrier for v in u.values] exact_value = np.dot(u.probabilities[leq_barrier], payoff[leq_barrier]) print("exact expected value:\t%.4f" % exact_value) num_state_qubits = asian_barrier_spread.num_qubits - asian_barrier_spread.num_ancillas print("state qubits: ", num_state_qubits) transpiled = transpile(asian_barrier_spread, basis_gates=["u", "cx"]) print("circuit width:", transpiled.width()) print("circuit depth:", transpiled.depth()) asian_barrier_spread_measure = asian_barrier_spread.measure_all(inplace=False) sampler = Sampler() job = sampler.run(asian_barrier_spread_measure) # evaluate the result value = 0 probabilities = job.result().quasi_dists[0].binary_probabilities() for i, prob in probabilities.items(): if prob > 1e-4 and i[-num_state_qubits:][0] == "1": value += prob # map value to original range mapped_value = objective.post_processing(value) / (2**num_uncertainty_qubits - 1) * (high_ - low_) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % mapped_value) print("Exact Expected Payoff: %.4f" % exact_value) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=asian_barrier_spread, objective_qubits=[objective_index], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation(epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100})) result = ae.estimate(problem) conf_int = ( np.array(result.confidence_interval_processed) / (2**num_uncertainty_qubits - 1) * (high_ - low_) ) print("Exact value: \t%.4f" % exact_value) print( "Estimated value:\t%.4f" % (result.estimation_processed / (2**num_uncertainty_qubits - 1) * (high_ - low_)) ) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt %matplotlib inline import numpy as np from qiskit import QuantumCircuit from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.circuit.library import NormalDistribution # can be used in case a principal component analysis has been done to derive the uncertainty model, ignored in this example. A = np.eye(2) b = np.zeros(2) # specify the number of qubits that are used to represent the different dimenions of the uncertainty model num_qubits = [2, 2] # specify the lower and upper bounds for the different dimension low = [0, 0] high = [0.12, 0.24] mu = [0.12, 0.24] sigma = 0.01 * np.eye(2) # construct corresponding distribution bounds = list(zip(low, high)) u = NormalDistribution(num_qubits, mu, sigma, bounds) # plot contour of probability density function x = np.linspace(low[0], high[0], 2 ** num_qubits[0]) y = np.linspace(low[1], high[1], 2 ** num_qubits[1]) z = u.probabilities.reshape(2 ** num_qubits[0], 2 ** num_qubits[1]) plt.contourf(x, y, z) plt.xticks(x, size=15) plt.yticks(y, size=15) plt.grid() plt.xlabel("$r_1$ (%)", size=15) plt.ylabel("$r_2$ (%)", size=15) plt.colorbar() plt.show() # specify cash flow cf = [1.0, 2.0] periods = range(1, len(cf) + 1) # plot cash flow plt.bar(periods, cf) plt.xticks(periods, size=15) plt.yticks(size=15) plt.grid() plt.xlabel("periods", size=15) plt.ylabel("cashflow ($)", size=15) plt.show() # estimate real value cnt = 0 exact_value = 0.0 for x1 in np.linspace(low[0], high[0], pow(2, num_qubits[0])): for x2 in np.linspace(low[1], high[1], pow(2, num_qubits[1])): prob = u.probabilities[cnt] for t in range(len(cf)): # evaluate linear approximation of real value w.r.t. interest rates exact_value += prob * ( cf[t] / pow(1 + b[t], t + 1) - (t + 1) * cf[t] * np.dot(A[:, t], np.asarray([x1, x2])) / pow(1 + b[t], t + 2) ) cnt += 1 print("Exact value: \t%.4f" % exact_value) # specify approximation factor c_approx = 0.125 # create fixed income pricing application from qiskit_finance.applications.estimation import FixedIncomePricing fixed_income = FixedIncomePricing( num_qubits=num_qubits, pca_matrix=A, initial_interests=b, cash_flow=cf, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=u, ) fixed_income._objective.draw() fixed_income_circ = QuantumCircuit(fixed_income._objective.num_qubits) # load probability distribution fixed_income_circ.append(u, range(u.num_qubits)) # apply function fixed_income_circ.append(fixed_income._objective, range(fixed_income._objective.num_qubits)) fixed_income_circ.draw() # set target precision and confidence level epsilon = 0.01 alpha = 0.05 # construct amplitude estimation problem = fixed_income.to_estimation_problem() ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % exact_value) print("Estimated value: \t%.4f" % (fixed_income.interpret(result))) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import numpy as np import matplotlib.pyplot as plt from qiskit import QuantumRegister, QuantumCircuit from qiskit.circuit.library import IntegerComparator from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler # set problem parameters n_z = 2 z_max = 2 z_values = np.linspace(-z_max, z_max, 2**n_z) p_zeros = [0.15, 0.25] rhos = [0.1, 0.05] lgd = [1, 2] K = len(p_zeros) alpha = 0.05 from qiskit_finance.circuit.library import GaussianConditionalIndependenceModel as GCI u = GCI(n_z, z_max, p_zeros, rhos) u.draw() u_measure = u.measure_all(inplace=False) sampler = Sampler() job = sampler.run(u_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # analyze uncertainty circuit and determine exact solutions p_z = np.zeros(2**n_z) p_default = np.zeros(K) values = [] probabilities = [] num_qubits = u.num_qubits for i, prob in binary_probabilities.items(): # extract value of Z and corresponding probability i_normal = int(i[-n_z:], 2) p_z[i_normal] += prob # determine overall default probability for k loss = 0 for k in range(K): if i[K - k - 1] == "1": p_default[k] += prob loss += lgd[k] values += [loss] probabilities += [prob] values = np.array(values) probabilities = np.array(probabilities) expected_loss = np.dot(values, probabilities) losses = np.sort(np.unique(values)) pdf = np.zeros(len(losses)) for i, v in enumerate(losses): pdf[i] += sum(probabilities[values == v]) cdf = np.cumsum(pdf) i_var = np.argmax(cdf >= 1 - alpha) exact_var = losses[i_var] exact_cvar = np.dot(pdf[(i_var + 1) :], losses[(i_var + 1) :]) / sum(pdf[(i_var + 1) :]) print("Expected Loss E[L]: %.4f" % expected_loss) print("Value at Risk VaR[L]: %.4f" % exact_var) print("P[L <= VaR[L]]: %.4f" % cdf[exact_var]) print("Conditional Value at Risk CVaR[L]: %.4f" % exact_cvar) # plot loss PDF, expected loss, var, and cvar plt.bar(losses, pdf) plt.axvline(expected_loss, color="green", linestyle="--", label="E[L]") plt.axvline(exact_var, color="orange", linestyle="--", label="VaR(L)") plt.axvline(exact_cvar, color="red", linestyle="--", label="CVaR(L)") plt.legend(fontsize=15) plt.xlabel("Loss L ($)", size=15) plt.ylabel("probability (%)", size=15) plt.title("Loss Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for Z plt.plot(z_values, p_z, "o-", linewidth=3, markersize=8) plt.grid() plt.xlabel("Z value", size=15) plt.ylabel("probability (%)", size=15) plt.title("Z Distribution", size=20) plt.xticks(size=15) plt.yticks(size=15) plt.show() # plot results for default probabilities plt.bar(range(K), p_default) plt.xlabel("Asset", size=15) plt.ylabel("probability (%)", size=15) plt.title("Individual Default Probabilities", size=20) plt.xticks(range(K), size=15) plt.yticks(size=15) plt.grid() plt.show() # add Z qubits with weight/loss 0 from qiskit.circuit.library import WeightedAdder agg = WeightedAdder(n_z + K, [0] * n_z + lgd) from qiskit.circuit.library import LinearAmplitudeFunction # define linear objective function breakpoints = [0] slopes = [1] offsets = [0] f_min = 0 f_max = sum(lgd) c_approx = 0.25 objective = LinearAmplitudeFunction( agg.num_sum_qubits, slope=slopes, offset=offsets, # max value that can be reached by the qubit register (will not always be reached) domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u.to_gate(), qr_state) # aggregate state_preparation.append(agg.to_gate(), qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(objective.to_gate(), qr_sum[:] + qr_obj[:]) # uncompute aggregation state_preparation.append(agg.to_gate().inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) # draw the circuit state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": value += prob print("Exact Expected Loss: %.4f" % expected_loss) print("Exact Operator Value: %.4f" % value) print("Mapped Operator value: %.4f" % objective.post_processing(value)) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=objective.post_processing, ) # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) # print results conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % expected_loss) print("Estimated value:\t%.4f" % result.estimation_processed) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) # set x value to estimate the CDF x_eval = 2 comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) comparator.draw() def get_cdf_circuit(x_eval): # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_compare = QuantumRegister(1, "compare") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # comparator objective function comparator = IntegerComparator(agg.num_sum_qubits, x_eval + 1, geq=False) state_preparation.append(comparator, qr_sum[:] + qr_obj[:] + qr_carry[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) return state_preparation state_preparation = get_cdf_circuit(x_eval) state_preparation.draw() state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result var_prob = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1) :][0] == "1": var_prob += prob print("Operator CDF(%s)" % x_eval + " = %.4f" % var_prob) print("Exact CDF(%s)" % x_eval + " = %.4f" % cdf[x_eval]) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem(state_preparation=state_preparation, objective_qubits=[len(qr_state)]) # construct amplitude estimation ae_cdf = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cdf = ae_cdf.estimate(problem) # print results conf_int = np.array(result_cdf.confidence_interval) print("Exact value: \t%.4f" % cdf[x_eval]) print("Estimated value:\t%.4f" % result_cdf.estimation) print("Confidence interval: \t[%.4f, %.4f]" % tuple(conf_int)) def run_ae_for_cdf(x_eval, epsilon=0.01, alpha=0.05, simulator="aer_simulator"): # construct amplitude estimation state_preparation = get_cdf_circuit(x_eval) problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)] ) ae_var = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_var = ae_var.estimate(problem) return result_var.estimation def bisection_search( objective, target_value, low_level, high_level, low_value=None, high_value=None ): """ Determines the smallest level such that the objective value is still larger than the target :param objective: objective function :param target: target value :param low_level: lowest level to be considered :param high_level: highest level to be considered :param low_value: value of lowest level (will be evaluated if set to None) :param high_value: value of highest level (will be evaluated if set to None) :return: dictionary with level, value, num_eval """ # check whether low and high values are given and evaluated them otherwise print("--------------------------------------------------------------------") print("start bisection search for target value %.3f" % target_value) print("--------------------------------------------------------------------") num_eval = 0 if low_value is None: low_value = objective(low_level) num_eval += 1 if high_value is None: high_value = objective(high_level) num_eval += 1 # check if low_value already satisfies the condition if low_value > target_value: return { "level": low_level, "value": low_value, "num_eval": num_eval, "comment": "returned low value", } elif low_value == target_value: return {"level": low_level, "value": low_value, "num_eval": num_eval, "comment": "success"} # check if high_value is above target if high_value < target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "returned low value", } elif high_value == target_value: return { "level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success", } # perform bisection search until print("low_level low_value level value high_level high_value") print("--------------------------------------------------------------------") while high_level - low_level > 1: level = int(np.round((high_level + low_level) / 2.0)) num_eval += 1 value = objective(level) print( "%2d %.3f %2d %.3f %2d %.3f" % (low_level, low_value, level, value, high_level, high_value) ) if value >= target_value: high_level = level high_value = value else: low_level = level low_value = value # return high value after bisection search print("--------------------------------------------------------------------") print("finished bisection search") print("--------------------------------------------------------------------") return {"level": high_level, "value": high_value, "num_eval": num_eval, "comment": "success"} # run bisection search to determine VaR objective = lambda x: run_ae_for_cdf(x) bisection_result = bisection_search( objective, 1 - alpha, min(losses) - 1, max(losses), low_value=0, high_value=1 ) var = bisection_result["level"] print("Estimated Value at Risk: %2d" % var) print("Exact Value at Risk: %2d" % exact_var) print("Estimated Probability: %.3f" % bisection_result["value"]) print("Exact Probability: %.3f" % cdf[exact_var]) # define linear objective breakpoints = [0, var] slopes = [0, 1] offsets = [0, 0] # subtract VaR and add it later to the estimate f_min = 0 f_max = 3 - var c_approx = 0.25 cvar_objective = LinearAmplitudeFunction( agg.num_sum_qubits, slopes, offsets, domain=(0, 2**agg.num_sum_qubits - 1), image=(f_min, f_max), rescaling_factor=c_approx, breakpoints=breakpoints, ) cvar_objective.draw() # define the registers for convenience and readability qr_state = QuantumRegister(u.num_qubits, "state") qr_sum = QuantumRegister(agg.num_sum_qubits, "sum") qr_carry = QuantumRegister(agg.num_carry_qubits, "carry") qr_obj = QuantumRegister(1, "objective") qr_work = QuantumRegister(cvar_objective.num_ancillas - len(qr_carry), "work") # define the circuit state_preparation = QuantumCircuit(qr_state, qr_obj, qr_sum, qr_carry, qr_work, name="A") # load the random variable state_preparation.append(u, qr_state) # aggregate state_preparation.append(agg, qr_state[:] + qr_sum[:] + qr_carry[:]) # linear objective function state_preparation.append(cvar_objective, qr_sum[:] + qr_obj[:] + qr_carry[:] + qr_work[:]) # uncompute aggregation state_preparation.append(agg.inverse(), qr_state[:] + qr_sum[:] + qr_carry[:]) state_preparation_measure = state_preparation.measure_all(inplace=False) sampler = Sampler() job = sampler.run(state_preparation_measure) binary_probabilities = job.result().quasi_dists[0].binary_probabilities() # evaluate the result value = 0 for i, prob in binary_probabilities.items(): if prob > 1e-6 and i[-(len(qr_state) + 1)] == "1": value += prob # normalize and add VaR to estimate value = cvar_objective.post_processing(value) d = 1.0 - bisection_result["value"] v = value / d if d != 0 else 0 normalized_value = v + var print("Estimated CVaR: %.4f" % normalized_value) print("Exact CVaR: %.4f" % exact_cvar) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = EstimationProblem( state_preparation=state_preparation, objective_qubits=[len(qr_state)], post_processing=cvar_objective.post_processing, ) # construct amplitude estimation ae_cvar = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result_cvar = ae_cvar.estimate(problem) # print results d = 1.0 - bisection_result["value"] v = result_cvar.estimation_processed / d if d != 0 else 0 print("Exact CVaR: \t%.4f" % exact_cvar) print("Estimated CVaR:\t%.4f" % (v + var)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
import matplotlib.pyplot as plt import numpy as np from qiskit.circuit import ParameterVector from qiskit.circuit.library import TwoLocal from qiskit.quantum_info import Statevector from qiskit.algorithms import IterativeAmplitudeEstimation, EstimationProblem from qiskit_aer.primitives import Sampler from qiskit_finance.applications.estimation import EuropeanCallPricing from qiskit_finance.circuit.library import NormalDistribution # Set upper and lower data values bounds = np.array([0.0, 7.0]) # Set number of qubits used in the uncertainty model num_qubits = 3 # Load the trained circuit parameters g_params = [0.29399714, 0.38853322, 0.9557694, 0.07245791, 6.02626428, 0.13537225] # Set an initial state for the generator circuit init_dist = NormalDistribution(num_qubits, mu=1.0, sigma=1.0, bounds=bounds) # construct the variational form var_form = TwoLocal(num_qubits, "ry", "cz", entanglement="circular", reps=1) # keep a list of the parameters so we can associate them to the list of numerical values # (otherwise we need a dictionary) theta = var_form.ordered_parameters # compose the generator circuit, this is the circuit loading the uncertainty model g_circuit = init_dist.compose(var_form) # set the strike price (should be within the low and the high value of the uncertainty) strike_price = 2 # set the approximation scaling for the payoff function c_approx = 0.25 # Evaluate trained probability distribution values = [ bounds[0] + (bounds[1] - bounds[0]) * x / (2**num_qubits - 1) for x in range(2**num_qubits) ] uncertainty_model = g_circuit.assign_parameters(dict(zip(theta, g_params))) amplitudes = Statevector.from_instruction(uncertainty_model).data x = np.array(values) y = np.abs(amplitudes) ** 2 # Sample from target probability distribution N = 100000 log_normal = np.random.lognormal(mean=1, sigma=1, size=N) log_normal = np.round(log_normal) log_normal = log_normal[log_normal <= 7] log_normal_samples = [] for i in range(8): log_normal_samples += [np.sum(log_normal == i)] log_normal_samples = np.array(log_normal_samples / sum(log_normal_samples)) # Plot distributions plt.bar(x, y, width=0.2, label="trained distribution", color="royalblue") 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.plot( log_normal_samples, "-o", color="deepskyblue", label="target distribution", linewidth=4, markersize=12, ) plt.legend(loc="best") plt.show() # Evaluate payoff for different distributions payoff = np.array([0, 0, 0, 1, 2, 3, 4, 5]) ep = np.dot(log_normal_samples, payoff) print("Analytically calculated expected payoff w.r.t. the target distribution: %.4f" % ep) ep_trained = np.dot(y, payoff) print("Analytically calculated expected payoff w.r.t. the trained distribution: %.4f" % ep_trained) # Plot exact payoff function (evaluated on the grid of the trained uncertainty model) x = np.array(values) y_strike = np.maximum(0, x - strike_price) plt.plot(x, y_strike, "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() # construct circuit for payoff function european_call_pricing = EuropeanCallPricing( num_qubits, strike_price=strike_price, rescaling_factor=c_approx, bounds=bounds, uncertainty_model=uncertainty_model, ) # set target precision and confidence level epsilon = 0.01 alpha = 0.05 problem = european_call_pricing.to_estimation_problem() # construct amplitude estimation ae = IterativeAmplitudeEstimation( epsilon_target=epsilon, alpha=alpha, sampler=Sampler(run_options={"shots": 100}) ) result = ae.estimate(problem) conf_int = np.array(result.confidence_interval_processed) print("Exact value: \t%.4f" % ep_trained) print("Estimated value: \t%.4f" % (result.estimation_processed)) print("Confidence interval:\t[%.4f, %.4f]" % tuple(conf_int)) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
%matplotlib inline from qiskit_finance import QiskitFinanceError from qiskit_finance.data_providers import * import datetime import matplotlib.pyplot as plt from pandas.plotting import register_matplotlib_converters register_matplotlib_converters() data = RandomDataProvider( tickers=["TICKER1", "TICKER2"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() means = data.get_mean_vector() print("Means:") print(means) rho = data.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = data.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(data._tickers): print(s) print(data._data[cnt]) data = RandomDataProvider( tickers=["CompanyA", "CompanyB", "CompanyC"], start=datetime.datetime(2015, 1, 1), end=datetime.datetime(2016, 1, 30), seed=1, ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() stocks = ["GOOG", "AAPL"] token = "REPLACE-ME" if token != "REPLACE-ME": try: wiki = WikipediaDataProvider( token=token, tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), ) wiki.run() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") if token != "REPLACE-ME": if wiki._data: if wiki._n <= 1: print( "Not enough wiki data to plot covariance or time-series similarity. Please use at least two tickers." ) else: rho = wiki.get_similarity_matrix() print("A time-series similarity measure:") print(rho) plt.imshow(rho) plt.show() cov = wiki.get_covariance_matrix() print("A covariance matrix:") print(cov) plt.imshow(cov) plt.show() else: print("No wiki data loaded.") if token != "REPLACE-ME": if wiki._data: print("The underlying evolution of stock prices:") for (cnt, s) in enumerate(stocks): plt.plot(wiki._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() for (cnt, s) in enumerate(stocks): print(s) print(wiki._data[cnt]) else: print("No wiki data loaded.") token = "REPLACE-ME" if token != "REPLACE-ME": try: nasdaq = DataOnDemandProvider( token=token, tickers=["GOOG", "AAPL"], start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 2), ) nasdaq.run() for (cnt, s) in enumerate(nasdaq._tickers): plt.plot(nasdaq._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") token = "REPLACE-ME" if token != "REPLACE-ME": try: lse = ExchangeDataProvider( token=token, tickers=["AEO", "ABBY", "ADIG", "ABF", "AEP", "AAL", "AGK", "AFN", "AAS", "AEFS"], stockmarket=StockMarket.LONDON, start=datetime.datetime(2018, 1, 1), end=datetime.datetime(2018, 12, 31), ) lse.run() for (cnt, s) in enumerate(lse._tickers): plt.plot(lse._data[cnt], label=s) plt.legend() plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: print(ex) print("Error retrieving data.") try: data = YahooDataProvider( tickers=["MSFT", "AAPL", "GOOG"], start=datetime.datetime(2021, 1, 1), end=datetime.datetime(2021, 12, 31), ) data.run() for (cnt, s) in enumerate(data._tickers): plt.plot(data._data[cnt], label=s) plt.legend(loc="upper center", bbox_to_anchor=(0.5, 1.1), ncol=3) plt.xticks(rotation=90) plt.show() except QiskitFinanceError as ex: data = None print(ex) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
p = 0.2 import numpy as np from qiskit.circuit import QuantumCircuit class BernoulliA(QuantumCircuit): """A circuit representing the Bernoulli A operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(theta_p, 0) class BernoulliQ(QuantumCircuit): """A circuit representing the Bernoulli Q operator.""" def __init__(self, probability): super().__init__(1) # circuit on 1 qubit self._theta_p = 2 * np.arcsin(np.sqrt(probability)) self.ry(2 * self._theta_p, 0) def power(self, k): # implement the efficient power of Q q_k = QuantumCircuit(1) q_k.ry(2 * k * self._theta_p, 0) return q_k A = BernoulliA(p) Q = BernoulliQ(p) from qiskit.algorithms import EstimationProblem problem = EstimationProblem( state_preparation=A, # A operator grover_operator=Q, # Q operator objective_qubits=[0], # the "good" state Psi1 is identified as measuring |1> in qubit 0 ) from qiskit.primitives import Sampler sampler = Sampler() from qiskit.algorithms import AmplitudeEstimation ae = AmplitudeEstimation( num_eval_qubits=3, # the number of evaluation qubits specifies circuit width and accuracy sampler=sampler, ) ae_result = ae.estimate(problem) print(ae_result.estimation) import matplotlib.pyplot as plt # plot estimated values gridpoints = list(ae_result.samples.keys()) probabilities = list(ae_result.samples.values()) plt.bar(gridpoints, probabilities, width=0.5 / len(probabilities)) plt.axvline(p, color="r", ls="--") plt.xticks(size=15) plt.yticks([0, 0.25, 0.5, 0.75, 1], size=15) plt.title("Estimated Values", size=15) plt.ylabel("Probability", size=15) plt.xlabel(r"Amplitude $a$", size=15) plt.ylim((0, 1)) plt.grid() plt.show() print("Interpolated MLE estimator:", ae_result.mle) ae_circuit = ae.construct_circuit(problem) ae_circuit.decompose().draw( "mpl", style="iqx" ) # decompose 1 level: exposes the Phase estimation circuit! from qiskit import transpile basis_gates = ["h", "ry", "cry", "cx", "ccx", "p", "cp", "x", "s", "sdg", "y", "t", "cz"] transpile(ae_circuit, basis_gates=basis_gates, optimization_level=2).draw("mpl", style="iqx") from qiskit.algorithms import IterativeAmplitudeEstimation iae = IterativeAmplitudeEstimation( epsilon_target=0.01, # target accuracy alpha=0.05, # width of the confidence interval sampler=sampler, ) iae_result = iae.estimate(problem) print("Estimate:", iae_result.estimation) iae_circuit = iae.construct_circuit(problem, k=3) iae_circuit.draw("mpl", style="iqx") from qiskit.algorithms import MaximumLikelihoodAmplitudeEstimation mlae = MaximumLikelihoodAmplitudeEstimation( evaluation_schedule=3, # log2 of the maximal Grover power sampler=sampler, ) mlae_result = mlae.estimate(problem) print("Estimate:", mlae_result.estimation) from qiskit.algorithms import FasterAmplitudeEstimation fae = FasterAmplitudeEstimation( delta=0.01, # target accuracy maxiter=3, # determines the maximal power of the Grover operator sampler=sampler, ) fae_result = fae.estimate(problem) print("Estimate:", fae_result.estimation) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit.result import QuasiDistribution from qiskit_aer.primitives import Sampler from qiskit_finance.applications.optimization import PortfolioOptimization from qiskit_finance.data_providers import RandomDataProvider from qiskit_optimization.algorithms import MinimumEigenOptimizer import numpy as np import matplotlib.pyplot as plt import datetime # set number of assets (= number of qubits) num_assets = 4 seed = 123 # Generate expected return and covariance matrix from (random) time-series stocks = [("TICKER%s" % i) for i in range(num_assets)] data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() mu = data.get_period_return_mean_vector() sigma = data.get_period_return_covariance_matrix() # plot sigma plt.imshow(sigma, interpolation="nearest") plt.show() q = 0.5 # set risk factor budget = num_assets // 2 # set budget penalty = num_assets # set parameter to scale the budget penalty term portfolio = PortfolioOptimization( expected_returns=mu, covariances=sigma, risk_factor=q, budget=budget ) qp = portfolio.to_quadratic_program() qp def print_result(result): selection = result.x value = result.fval print("Optimal: selection {}, value {:.4f}".format(selection, value)) eigenstate = result.min_eigen_solver_result.eigenstate probabilities = ( eigenstate.binary_probabilities() if isinstance(eigenstate, QuasiDistribution) else {k: np.abs(v) ** 2 for k, v in eigenstate.to_dict().items()} ) print("\n----------------- Full result ---------------------") print("selection\tvalue\t\tprobability") print("---------------------------------------------------") probabilities = sorted(probabilities.items(), key=lambda x: x[1], reverse=True) for k, v in probabilities: x = np.array([int(i) for i in list(reversed(k))]) value = portfolio.to_quadratic_program().objective.evaluate(x) print("%10s\t%.4f\t\t%.4f" % (x, value, v)) exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(qp) print_result(result) from qiskit.utils import algorithm_globals algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=500) ry = TwoLocal(num_assets, "ry", "cz", reps=3, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(qp) print_result(result) algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(qp) print_result(result) import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright
https://github.com/qiskit-community/qiskit-translations-staging
qiskit-community
# Import requisite modules import math import datetime import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Import Qiskit packages from qiskit.algorithms.minimum_eigensolvers import NumPyMinimumEigensolver, QAOA, SamplingVQE from qiskit.algorithms.optimizers import COBYLA from qiskit.circuit.library import TwoLocal from qiskit_aer.primitives import Sampler from qiskit_optimization.algorithms import MinimumEigenOptimizer # The data providers of stock-market data from qiskit_finance.data_providers import RandomDataProvider from qiskit_finance.applications.optimization import PortfolioDiversification # Generate a pairwise time-series similarity matrix seed = 123 stocks = ["TICKER1", "TICKER2"] n = len(stocks) data = RandomDataProvider( tickers=stocks, start=datetime.datetime(2016, 1, 1), end=datetime.datetime(2016, 1, 30), seed=seed, ) data.run() rho = data.get_similarity_matrix() q = 1 # q less or equal than n class ClassicalOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n # number of inner variables self.q = q # number of required selection def compute_allowed_combinations(self): f = math.factorial return int(f(self.n) / f(self.q) / f(self.n - self.q)) def cplex_solution(self): # refactoring rho = self.rho n = self.n q = self.q my_obj = list(rho.reshape(1, n**2)[0]) + [0.0 for x in range(0, n)] my_ub = [1 for x in range(0, n**2 + n)] my_lb = [0 for x in range(0, n**2 + n)] my_ctype = "".join(["I" for x in range(0, n**2 + n)]) my_rhs = ( [q] + [1 for x in range(0, n)] + [0 for x in range(0, n)] + [0.1 for x in range(0, n**2)] ) my_sense = ( "".join(["E" for x in range(0, 1 + n)]) + "".join(["E" for x in range(0, n)]) + "".join(["L" for x in range(0, n**2)]) ) try: my_prob = cplex.Cplex() self.populatebyrow(my_prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs) my_prob.solve() except CplexError as exc: print(exc) return x = my_prob.solution.get_values() x = np.array(x) cost = my_prob.solution.get_objective_value() return x, cost def populatebyrow(self, prob, my_obj, my_ub, my_lb, my_ctype, my_sense, my_rhs): n = self.n prob.objective.set_sense(prob.objective.sense.minimize) prob.variables.add(obj=my_obj, lb=my_lb, ub=my_ub, types=my_ctype) prob.set_log_stream(None) prob.set_error_stream(None) prob.set_warning_stream(None) prob.set_results_stream(None) rows = [] col = [x for x in range(n**2, n**2 + n)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [x for x in range(0 + n * ii, n + n * ii)] coef = [1 for x in range(0, n)] rows.append([col, coef]) for ii in range(0, n): col = [ii * n + ii, n**2 + ii] coef = [1, -1] rows.append([col, coef]) for ii in range(0, n): for jj in range(0, n): col = [ii * n + jj, n**2 + jj] coef = [1, -1] rows.append([col, coef]) prob.linear_constraints.add(lin_expr=rows, senses=my_sense, rhs=my_rhs) # Instantiate the classical optimizer class classical_optimizer = ClassicalOptimizer(rho, n, q) # Compute the number of feasible solutions: print("Number of feasible combinations= " + str(classical_optimizer.compute_allowed_combinations())) # Compute the total number of possible combinations (feasible + unfeasible) print("Total number of combinations= " + str(2 ** (n * (n + 1)))) # Visualize the solution def visualize_solution(xc, yc, x, C, n, K, title_str): plt.figure() plt.scatter(xc, yc, s=200) for i in range(len(xc)): plt.annotate(i, (xc[i] + 0.015, yc[i]), size=16, color="r") plt.grid() for ii in range(n**2, n**2 + n): if x[ii] > 0: plt.plot(xc[ii - n**2], yc[ii - n**2], "r*", ms=20) for ii in range(0, n**2): if x[ii] > 0: iy = ii // n ix = ii % n plt.plot([xc[ix], xc[iy]], [yc[ix], yc[iy]], "C2") plt.title(title_str + " cost = " + str(int(C * 100) / 100.0)) plt.show() from qiskit.utils import algorithm_globals class QuantumOptimizer: def __init__(self, rho, n, q): self.rho = rho self.n = n self.q = q self.pdf = PortfolioDiversification(similarity_matrix=rho, num_assets=n, num_clusters=q) self.qp = self.pdf.to_quadratic_program() # Obtains the least eigenvalue of the Hamiltonian classically def exact_solution(self): exact_mes = NumPyMinimumEigensolver() exact_eigensolver = MinimumEigenOptimizer(exact_mes) result = exact_eigensolver.solve(self.qp) return self.decode_result(result) def vqe_solution(self): algorithm_globals.random_seed = 100 cobyla = COBYLA() cobyla.set_options(maxiter=250) ry = TwoLocal(n, "ry", "cz", reps=5, entanglement="full") vqe_mes = SamplingVQE(sampler=Sampler(), ansatz=ry, optimizer=cobyla) vqe = MinimumEigenOptimizer(vqe_mes) result = vqe.solve(self.qp) return self.decode_result(result) def qaoa_solution(self): algorithm_globals.random_seed = 1234 cobyla = COBYLA() cobyla.set_options(maxiter=250) qaoa_mes = QAOA(sampler=Sampler(), optimizer=cobyla, reps=3) qaoa = MinimumEigenOptimizer(qaoa_mes) result = qaoa.solve(self.qp) return self.decode_result(result) def decode_result(self, result, offset=0): quantum_solution = 1 - (result.x) ground_level = self.qp.objective.evaluate(result.x) return quantum_solution, ground_level # Instantiate the quantum optimizer class with parameters: quantum_optimizer = QuantumOptimizer(rho, n, q) # Check if the binary representation is correct. This requires CPLEX try: import cplex # warnings.filterwarnings('ignore') quantum_solution, quantum_cost = quantum_optimizer.exact_solution() print(quantum_solution, quantum_cost) classical_solution, classical_cost = classical_optimizer.cplex_solution() print(classical_solution, classical_cost) if np.abs(quantum_cost - classical_cost) < 0.01: print("Binary formulation is correct") else: print("Error in the formulation of the Hamiltonian") except Exception as ex: print(ex) ground_state, ground_level = quantum_optimizer.exact_solution() print(ground_state) classical_cost = 1.000779571614484 # obtained from the CPLEX solution try: if np.abs(ground_level - classical_cost) < 0.01: print("Ising Hamiltonian in Z basis is correct") else: print("Error in the Ising Hamiltonian formulation") except Exception as ex: print(ex) vqe_state, vqe_level = quantum_optimizer.vqe_solution() print(vqe_state, vqe_level) try: if np.linalg.norm(ground_state - vqe_state) < 0.01: print("SamplingVQE produces the same solution as the exact eigensolver.") else: print( "SamplingVQE does not produce the same solution as the exact eigensolver, but that is to be expected." ) except Exception as ex: print(ex) xc, yc = data.get_coordinates() visualize_solution(xc, yc, ground_state, ground_level, n, q, "Classical") visualize_solution(xc, yc, vqe_state, vqe_level, n, q, "VQE") import qiskit.tools.jupyter %qiskit_version_table %qiskit_copyright