├── .DS_Store ├── Deep-Solver-Jumps-master-github ├── .DS_Store ├── Descrizione Cartelle e Script.txt ├── equation.py ├── script_expectation.py ├── script_basket_option.py ├── script_call_optionCGMY.py ├── PureJumpEquation.py ├── CGMY.py ├── PureJumpEquation_CGMYprova.py ├── PureJumpSolver.py └── script_call_option.py ├── README.md └── LICENSE /.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlessandroGnoatto/DeepBsdeSolverWithJumps/HEAD/.DS_Store -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/.DS_Store: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/AlessandroGnoatto/DeepBsdeSolverWithJumps/HEAD/Deep-Solver-Jumps-master-github/.DS_Store -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Deep BSDE solver with jumps in Python 2 | 3 | 4 | ## How to run the examples 5 | 6 | For each example in the paper you can find a dedicated script. 7 | 8 | * script_expectation.py: a simple test for the martingale property. 9 | * script_call_option.py: a call option on one asset following a Merton jump diffusion. 10 | * script_basket_option.py: a basket call on 100 assets each following a Merton jump diffusion. 11 | * script_call_option_CGMY.py: an example in dimension one with infinite activity. 12 | 13 | 14 | 15 | 16 | 17 | 18 | ## Dependencies 19 | 20 | * [Tensorflow](https://github.com/tensorflow/tensorflow) 21 | 22 | ## Reference 23 | [1] Andersson, K. Gnoatto, A., Patacca, M., Picarelli, A. A Deep Solver for BSDEs with Jumps. https://arxiv.org/abs/2211.04349 24 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/Descrizione Cartelle e Script.txt: -------------------------------------------------------------------------------- 1 | Legenda Cartelle 2 | 3 | In 20220518_Deep-Solver-master PureJump_ez_Screenshot e 20220615_Deep-Solver-master PureJump_ez_Screenshot ci sono gli screenshot delle varie prove effettuate (i risultati sono condensati nella sezione empirica del paper) 4 | 5 | Nelle cartelle 20220616_Deep-Solver-master PureJump_ez_AG e 20220616_Deep-Solver-master PureJump_ez_MP ci sono i codici definitivi utilizzati per le simulazioni finali riportate nella sezione empirica del paper 6 | 7 | AG e MP differiscono solo per la riga 37 di PureJumpSolver per il resto sono completamente uguali (i risultati della sezione empirica del paper sono tutti calcolati con MP) 8 | 9 | 20221005_Deep-Solver-master PureJump_ez_MP è la copia di 20220616_Deep-Solver-master PureJump_ez_MP, cambia solo che è stata aggiunto la classe CGMY 10 | 11 | File CGMY è uguale a CGMY_prova2, cambia che è stato adeguato per essere inserito nel solver 12 | 13 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/equation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | class Equation(object): 5 | """Base class for defining PDE related function.""" 6 | 7 | def __init__(self, eqn_config): 8 | self.dim = eqn_config.dim 9 | self.total_time = eqn_config.total_time 10 | self.num_time_interval = eqn_config.num_time_interval 11 | self.delta_t = self.total_time / self.num_time_interval 12 | self.sqrt_delta_t = np.sqrt(self.delta_t) 13 | self.y_init = None 14 | 15 | def sample(self, num_sample): 16 | """Sample forward SDE.""" 17 | raise NotImplementedError 18 | 19 | def f_tf(self, t, x, y, z): 20 | """Generator function in the PDE.""" 21 | raise NotImplementedError 22 | 23 | def g_tf(self, t, x): 24 | """Terminal condition of the PDE.""" 25 | raise NotImplementedError 26 | 27 | def getFsdeDiffusion(self, t, x): 28 | """Diffusion term of the fwd SDE""" 29 | raise NotImplementedError 30 | 31 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/script_expectation.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import tensorflow as tf 4 | from PureJumpSolver import BSDESolver 5 | import PureJumpEquation as eqn 6 | import munch 7 | from scipy.stats import norm 8 | import pandas as pd 9 | 10 | 11 | 12 | if __name__ == "__main__": 13 | dim = 1 #dimension of brownian motion 14 | P = 2048*8 #number of outer Monte Carlo Loops 15 | batch_size = 64 16 | total_time = 1.0 17 | num_time_interval=40 18 | strike = 0.9 19 | lamb = 0.3 20 | r = 0.0 21 | sigma=0.25 22 | aver_jump = 0.5 23 | var_jump = 0.25 24 | x_init=1 25 | config = { 26 | "eqn_config": { 27 | "_comment": "a call contract", 28 | "eqn_name": "Expectation", 29 | "total_time": total_time, 30 | "dim": dim, 31 | "num_time_interval": num_time_interval, 32 | "strike":strike, 33 | "r":r, 34 | "sigma":sigma, 35 | "lamb":lamb, 36 | "aver_jump":aver_jump, 37 | "var_jump":var_jump, 38 | "x_init":x_init, 39 | "u": 1 40 | 41 | }, 42 | "net_config": { 43 | "num_hiddens": [dim+20, dim+20], 44 | "lr_values": [5e-2, 5e-3], 45 | "lr_boundaries": [4000], 46 | "num_iterations": 8000, 47 | "batch_size": batch_size, 48 | "valid_size": 256, 49 | "logging_frequency": 100, 50 | "dtype": "float64", 51 | "verbose": True 52 | } 53 | } 54 | config = munch.munchify(config) 55 | bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config) 56 | tf.keras.backend.set_floatx(config.net_config.dtype) 57 | 58 | #apply algorithm 1 59 | bsde_solver = BSDESolver(config, bsde) 60 | training_history = bsde_solver.train() 61 | 62 | #Simulate the BSDE after training - MtM scenarios 63 | simulations = bsde_solver.model.simulate_path(bsde.sample(P)) 64 | 65 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/script_basket_option.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import tensorflow as tf 4 | from PureJumpSolver import BSDESolver 5 | import PureJumpEquation as eqn 6 | import munch 7 | from scipy.stats import norm 8 | import pandas as pd 9 | 10 | plt.rcParams['figure.dpi'] = 300 11 | 12 | 13 | 14 | if __name__ == "__main__": 15 | dim = 5 #dimension of brownian motion 16 | P = 2**12 #number of outer Monte Carlo Loops 17 | batch_size = 2**10 18 | total_time = 1.0 19 | num_time_interval = 40 20 | strike = 0.9 21 | lamb = 0.3 22 | r = 0.05 23 | sigma = 0.25 24 | aver_jump = 0.5 25 | var_jump = 0.25**2 26 | x_init = 1.0 27 | config = { 28 | "eqn_config": { 29 | "_comment": "a basket call option", 30 | "eqn_name": "BasketOption", 31 | "total_time": total_time, 32 | "dim": dim, 33 | "num_time_interval": num_time_interval, 34 | "strike":strike, 35 | "r":r, 36 | "sigma":sigma, 37 | "lamb":lamb, 38 | "aver_jump":aver_jump, 39 | "var_jump":var_jump, 40 | "x_init":x_init, 41 | 42 | }, 43 | "net_config": { 44 | "num_hiddens": [15,15], 45 | "lr_values": [1.0e-1, 5e-2, 1e-2, 5e-3, 1e-3, 5e-4], 46 | "lr_boundaries": [1000,3000,5000, 7000, 10000],#d=5#"lr_boundaries": [1000,4000, 8000, 12000, 15000],#d=25#"lr_boundaries": [5000,10000,15000, 20000, 23000], # 47 | "num_iterations": 10000, 48 | "batch_size": batch_size, 49 | "valid_size": 256, 50 | "logging_frequency": 100, 51 | "dtype": "float64", 52 | "y_init_range": [0.24, 0.4], 53 | "verbose": True 54 | } 55 | } 56 | config = munch.munchify(config) 57 | bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config) 58 | tf.keras.backend.set_floatx(config.net_config.dtype) 59 | 60 | #Monte Carlo Price 61 | samples = bsde.sample(P) 62 | stock = samples[0] 63 | #mcprice = np.exp(-r* total_time)*np.average(np.maximum(np.sum(stock[:,:,-1],1) - dim * strike,0)) 64 | #payoff = np.maximum(np.sum(stock[:,:,-1],1) - dim * strike,0) 65 | mcprice = np.exp(-r* total_time)*np.average(np.maximum(1/dim * np.sum(stock[:,:,-1],1) - strike,0)) 66 | payoff = np.maximum(1/dim * np.sum(stock[:,:,-1],1) - strike,0) 67 | np.disp(mcprice) 68 | 69 | #apply algorithm 1 70 | bsde_solver = BSDESolver(config, bsde) 71 | training_history = bsde_solver.train() 72 | 73 | #Simulate the BSDE after training - MtM scenarios 74 | simulations = bsde_solver.model.simulate_path(samples) 75 | 76 | fig = plt.figure() 77 | plt.plot(simulations[0:10,0,:].T) 78 | plt.xlabel('Time step') 79 | plt.ylabel('Y') 80 | plt.show() 81 | 82 | 83 | 84 | 85 | # mcprice = 14.426902897231209 86 | 87 | # np.save("training_history_dim_"+str(dim),training_history) 88 | # np.save("mcprice_dim_"+str(dim),mcprice) 89 | 90 | 91 | 92 | 93 | #%% 94 | #Simulate the BSDE after training - MtM scenarios 95 | samples = bsde.sample(P*2**4) 96 | #samples = bsde.sample(2**6) 97 | 98 | simulations = bsde_solver.model.simulate_path(samples) 99 | 100 | fig = plt.figure() 101 | plt.plot(simulations[0:10,0,:].T) 102 | plt.xlabel('Time step') 103 | plt.ylabel('Y') 104 | plt.show() 105 | 106 | 107 | 108 | # Monte Carlo Price 109 | stock = samples[0] 110 | #mcprice = np.exp(-r * total_time)*np.average(np.maximum(np.sum(stock[:,:,-1],1) - dim * strike,0)) 111 | mcprice = np.exp(-r * total_time)*np.average(np.maximum(1 / dim * np.sum(stock[:,:,-1],1) - strike,0)) 112 | 113 | #payoff = np.maximum(np.sum(stock[:,:,-1],1) - dim * strike,0) 114 | payoff = np.maximum(1 / dim * np.sum(stock[:,:,-1],1) - strike,0) 115 | 116 | np.disp(mcprice) 117 | 118 | # np.save("training_history_dim_"+str(dim),training_history) 119 | # np.save("mcprice_dim_"+str(dim),mcprice) 120 | 121 | #%% 122 | # Create the plot with a specific figure size 123 | NN = np.int(10000/100) 124 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 125 | 126 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 127 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Ref.)', linewidth=2) 128 | 129 | # Add labels and title 130 | plt.xlabel('Number of iterations') 131 | plt.ylabel('Y') 132 | plt.legend() 133 | plt.grid() 134 | plt.show() 135 | 136 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 137 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 138 | 139 | # Add labels and title 140 | plt.xlabel('Number of batch iterations') 141 | plt.yscale('log') 142 | plt.legend() 143 | plt.grid() 144 | 145 | # Show the plot 146 | plt.figure() 147 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 148 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Ref.)', linewidth=2) 149 | 150 | # Add labels and title 151 | plt.xlabel('Number of iterations') 152 | plt.ylabel('Y') 153 | plt.legend() 154 | plt.grid() 155 | 156 | plt.figure() 157 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 158 | 159 | # Add labels and title 160 | plt.xlabel('Number of batch iterations') 161 | plt.yscale('log') 162 | plt.legend() 163 | plt.grid() 164 | plt.show() 165 | 166 | 167 | #%% 168 | from scipy.stats import multivariate_normal as normal 169 | num_sample = 2**12 170 | t = np.linspace(0, total_time, num_time_interval + 1) 171 | delta_t = total_time/num_time_interval 172 | # simulazione del Browniano 173 | start = 0 174 | Y_MC_5 = np.zeros([5,num_time_interval + 1]) 175 | for nn in range(start, start+5): 176 | X_path = stock[nn,:,:] 177 | Y_MC = np.zeros(num_time_interval + 1) 178 | Y_MC[0] = np.exp(-r * total_time) * np.mean(np.maximum(np.sum(stock[:,:,-1],1) - dim * strike,0)) 179 | for n in range(0,num_time_interval): 180 | dw_sample = normal.rvs(size=[num_sample,dim,num_time_interval - n]) * np.sqrt(delta_t) 181 | if num_time_interval - n < 2: 182 | dw_sample = np.expand_dims(dw_sample,axis=2) 183 | if dim==1: 184 | dw_sample = np.expand_dims(dw_sample,axis=0) 185 | dw_sample = np.swapaxes(dw_sample,0,1) 186 | 187 | # simulazione dei salti 188 | 189 | eta = normal.rvs(mean=0.0 ,cov=1.0, size = [num_sample, dim, num_time_interval - n]) 190 | eta = np.reshape(eta,[num_sample, dim, num_time_interval - n]) 191 | 192 | Poisson = np.random.poisson(lamb * delta_t, [num_sample, dim , num_time_interval - n]) 193 | 194 | jumps = np.multiply(Poisson, aver_jump) + np.sqrt(var_jump)*np.multiply(np.sqrt(Poisson),eta) 195 | 196 | 197 | # traiettorie forward 198 | x_sample = np.ones([num_sample, dim, num_time_interval + 1 - n]) 199 | x_sample[:, :, 0] = np.ones([num_sample, dim]) * X_path[:,n] 200 | 201 | factor = np.exp((r-(sigma**2)/2)*delta_t - lamb*(np.exp(aver_jump + 0.5*var_jump)-1)*delta_t) 202 | 203 | for i in range(num_time_interval - n): 204 | x_sample[:, :, i + 1] = (factor * np.exp(sigma * dw_sample[:, :, i]) * np.exp(jumps[:, :, i])) * x_sample[:, :, i] 205 | 206 | #Y_MC[n] = np.exp(-r * (total_time - n*delta_t) ) * np.mean(np.maximum(np.sum(x_sample[:,:,-1],1) - dim * strike,0)) 207 | Y_MC[n] = np.exp(-r * (total_time - n*delta_t) ) * np.mean(np.maximum(1 / dim * np.sum(x_sample[:,:,-1],1) - strike,0)) 208 | 209 | if n == 0: 210 | plt.plot(np.mean(np.mean(x_sample,0),0)) 211 | plt.plot(np.exp(r*t)) 212 | Y_MC[-1] = payoff[nn] 213 | Y_MC_5[nn-start,:] = Y_MC 214 | 215 | plt.figure() 216 | for nn in range(start, start+5): 217 | plt.plot(t, simulations[nn,0,:], color='red') 218 | plt.plot(t, Y_MC_5[nn-start,:], '--', color='black') 219 | plt.plot(total_time, payoff[nn], 'x', color = 'black') 220 | plt.grid() 221 | plt.legend(['Y (Approx.)','Y (Ref.)']) 222 | 223 | 224 | 225 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/script_call_optionCGMY.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import matplotlib.pyplot as plt 3 | import tensorflow as tf 4 | from PureJumpSolver import BSDESolver 5 | import PureJumpEquation_CGMYprova as eqn 6 | import munch 7 | from scipy.stats import norm 8 | import pandas as pd 9 | from CGMY import CallPricingFFT 10 | 11 | plt.rcParams['figure.dpi'] = 300 12 | 13 | 14 | 15 | if __name__ == "__main__": 16 | dim = 1 #dimension of brownian motion 17 | P = 2**16 #number of outer Monte Carlo Loops 18 | batch_size = 2**7 19 | total_time = 1.0 20 | num_time_interval = 100 21 | strike = 0.9 22 | lamb = 0.3 23 | r = 0.04 24 | # sigma = 0.25 25 | aver_jump = 0.5 26 | var_jump = 0.25**2 27 | x_init = 1.0 28 | C=0.15 29 | G=13. 30 | M=14. 31 | Y=0.6 32 | 33 | eps = 0.00001 34 | d = 0 # è il dividend yield 35 | # h = 0.01 è il delta_t 36 | # n = 100 è il num_time_interval 37 | # Npaths = int(1e3) è la P 38 | config = { 39 | "eqn_config": { 40 | "_comment": "a call contract with CGMY", 41 | "eqn_name": "CallOptionCGMY", 42 | "total_time": total_time, 43 | "dim": dim, 44 | "num_time_interval": num_time_interval, 45 | "strike":strike, 46 | "r":r, 47 | #"sigma":sigma, 48 | "lamb":lamb, 49 | "aver_jump":aver_jump, 50 | "var_jump":var_jump, 51 | "x_init":x_init, 52 | "C":C, 53 | "G":G, 54 | "M":M, 55 | "Y":Y, 56 | "eps":eps, 57 | "d":d, 58 | }, 59 | "net_config": { 60 | "num_hiddens": [20,20], 61 | "lr_values": [1.0e-1, 5e-2, 1e-2, 5e-3, 1e-3, 5e-4],#"lr_values": [5e-2, 5e-3, 5e-4, 1e-4], 62 | "lr_boundaries": [1000, 2000, 3000, 4000, 5000], #"lr_values": [5e-2, 5e-3], 63 | "num_iterations": 6000, 64 | "batch_size": batch_size, 65 | "valid_size": 256, 66 | "logging_frequency": 100, 67 | "dtype": "float64", 68 | "y_init_range": [0., 0.3], 69 | "verbose": True 70 | } 71 | } 72 | 73 | config = munch.munchify(config) 74 | bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config) 75 | tf.keras.backend.set_floatx(config.net_config.dtype) 76 | 77 | #apply algorithm 1 78 | bsde_solver = BSDESolver(config, bsde) 79 | training_history = bsde_solver.train() 80 | 81 | #Simulate the BSDE after training - MtM scenarios 82 | samples = bsde.sample(P) 83 | simulations = bsde_solver.model.simulate_path(samples) 84 | 85 | fig = plt.figure() 86 | plt.plot(simulations[0:10,0,:].T) 87 | plt.xlabel('Time step') 88 | plt.ylabel('Y') 89 | plt.show() 90 | 91 | 92 | 93 | 94 | """ 95 | Monte Carlo Price 96 | """ 97 | stock = samples[0] 98 | mcprice = np.exp(-r* total_time)*np.average(np.maximum(stock[:,0,-1] - strike,0)) 99 | np.disp(mcprice) 100 | 101 | 102 | 103 | 104 | #%% 105 | #Simulate the BSDE after training - MtM scenarios 106 | #samples = bsde.sample(P) 107 | samples = bsde.sample(2**6) 108 | 109 | simulations = bsde_solver.model.simulate_path(samples) 110 | 111 | fig = plt.figure() 112 | plt.plot(simulations[0:10,0,:].T) 113 | plt.xlabel('Time step') 114 | plt.ylabel('Y') 115 | plt.show() 116 | 117 | 118 | 119 | 120 | """ 121 | Monte Carlo Price 122 | """ 123 | stock = samples[0] 124 | mcprice = np.exp(-r* total_time)*np.average(np.maximum(stock[:,0,-1] - strike,0)) 125 | np.disp(mcprice) 126 | 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | #%% 136 | # Create the plot with a specific figure size 137 | NN = np.int(6000/100) 138 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 139 | 140 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 141 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Ref.)', linewidth=2) 142 | mcprice = 0.1375305233367931 # FFT price 143 | 144 | # Add labels and title 145 | plt.xlabel('Number of iterations') 146 | plt.ylabel('Y') 147 | plt.legend() 148 | plt.grid() 149 | plt.show() 150 | 151 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 152 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 153 | 154 | # Add labels and title 155 | plt.xlabel('Number of batch iterations') 156 | plt.yscale('log') 157 | plt.legend() 158 | plt.grid() 159 | 160 | # Show the plot 161 | plt.figure() 162 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 163 | plt.plot(training_history[:NN,0], np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Ref.)', linewidth=2) 164 | # Add labels and title 165 | plt.xlabel('Number of iterations') 166 | plt.ylabel('Y') 167 | plt.legend() 168 | plt.grid() 169 | 170 | # Show the plot 171 | plt.figure() 172 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 173 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Ref.)', linewidth=2) 174 | 175 | # Add labels and title 176 | plt.xlabel('Number of iterations') 177 | plt.ylabel('Y') 178 | plt.legend() 179 | plt.grid() 180 | 181 | plt.figure() 182 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 183 | 184 | # Add labels and title 185 | plt.xlabel('Number of batch iterations') 186 | plt.yscale('log') 187 | plt.legend() 188 | plt.grid() 189 | plt.show() 190 | 191 | 192 | #%% 193 | import random 194 | plt.rcParams['figure.dpi'] = 100 195 | P = 2**3 196 | delta_t = 1/100 197 | # Simulate the BSDE after training - MtM scenarios 198 | samples = bsde.sample(P) 199 | pay_off = np.maximum(samples[0][:,0,-1] - strike ,0) 200 | simulations = bsde_solver.model.simulate_path(samples) # Y 201 | t = np.linspace(0,total_time,num_time_interval+1) 202 | err_T = simulations[:,0,-1] - pay_off 203 | #history_pred = bsde_solver.model.predict_step(samples) 204 | 205 | color = ['blue', 'red', 'green', 'purple', 'orange', 'black', 'grey', 'magenta', 'cyan'] 206 | 207 | f_compensator = np.zeros((P,num_time_interval)) # NN_n (S_n) 208 | NN_jump = np.zeros((P,num_time_interval)) 209 | f_jump = np.zeros((P,num_time_interval)) 210 | Z = np.zeros((P,num_time_interval)) 211 | one_net = False 212 | for time in range(0, num_time_interval): 213 | assetprice = samples[0][:, 0, time] 214 | jumped_assetprice = samples[0][:, 0, time] * np.exp(samples[2][:,0,time]) 215 | 216 | #price_approx[omega, time] = bsde_solver.model.subnet[time].call(np.reshape(assetprice, [1, 1]), training=False) 217 | #price_exact[omega, time] = merton_jump_call(assetprice, strike, total_time - time * delta_t, r, sigma, aver_jump, std_jump, lamb) 218 | if one_net: 219 | time_vector = np.ones(P)*time 220 | input_comp = np.array([time_vector, assetprice], dtype = np.float64).T 221 | f_compensator[:, time] = bsde_solver.model.subnet[0](input_comp, training=False)[:,0] 222 | 223 | #input_jump = np.reshape(np.array([time, assetprice, jumped_assetprice], dtype=np.float64), (P, 3)) 224 | input_jump = np.array([time_vector, assetprice], dtype = np.float64).T 225 | NN_jump[:, time] = bsde_solver.model.subnetCompensator[0](input_jump,training=False)[:,0] 226 | 227 | input_Z = np.array([time_vector, assetprice], dtype = np.float64).T 228 | Z[:, time] = bsde_solver.model.subnetControl[0](input_Z, training=False)[:,0] 229 | 230 | else: 231 | f_compensator[:, time] = bsde_solver.model.subnet[0](np.reshape([samples[0][:, 0, time]], [P, 1]), training=False)[:,0] 232 | 233 | NN_jump[:, time] = bsde_solver.model.subnetCompensator[time](np.reshape([samples[0][:, 0, time], samples[0][:, 0, time]*np.exp(samples[2][:,0,time])], [P, 2]),training=False)[:,0] 234 | #NN_jump[:, time] = bsde_solver.model.subnetCompensator[0](np.reshape([samples[0][:, 0, time]], [P, 1]),training=False)[:,0] 235 | Z[:, time] = bsde_solver.model.subnetControl[time](np.reshape([assetprice], [P, 1]), training=False)[:,0] 236 | f_jump[:, time] = NN_jump[:, time] * (jumped_assetprice - assetprice) 237 | 238 | FFT_price = np.zeros([5,num_time_interval+1]) 239 | for n in range(0,5): 240 | for i in range(0,num_time_interval+1): 241 | FFT_price[n,i] = CallPricingFFT(16,samples[0][n,0,i],strike,total_time - i *delta_t,r,0,C,G,M,Y) 242 | compensated_jumps = f_jump - f_compensator * delta_t 243 | 244 | plt.plot(NN_jump[0,:]) 245 | plt.plot(f_jump[0,:]) 246 | 247 | plt.figure() 248 | plt.plot(t,simulations[:5, 0, :].T,color = 'red') 249 | plt.plot(t[-1]*np.ones(5), pay_off[:5],'x', color='black') 250 | plt.plot(t, samples[0][:5,0,:].T, '--', color = 'black') 251 | plt.legend(['Y (Approx.)','Y (Ref.)']) 252 | plt.grid() 253 | plt.show() 254 | 255 | n = 0 256 | 257 | if strike < 0.0001: 258 | for omega in range(n,n+5): 259 | plt.plot(t, simulations[omega, 0, :], color='red') 260 | plt.plot(t, samples[0][omega,0,:], '--', color='black') 261 | plt.plot(t[-1], pay_off[omega], 'x', color = 'black') 262 | else: 263 | for omega in range(n,n+5): 264 | plt.plot(t, simulations[omega, 0, :], color='red') 265 | plt.plot(t, FFT_price[omega,:], '--', color='black') 266 | plt.plot(t[0], mcprice, 'd', color='black') 267 | plt.plot(t[-1], pay_off[omega], 'x', color = 'black') 268 | 269 | plt.grid() 270 | plt.legend(['Y (Approx.)','Y (Ref.)']) 271 | 272 | 273 | 274 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/PureJumpEquation.py: -------------------------------------------------------------------------------- 1 | from equation import Equation 2 | import numpy as np 3 | import tensorflow as tf 4 | from scipy.stats import multivariate_normal as normal 5 | 6 | 7 | class Expectation(Equation): 8 | def __init__(self,eqn_config): 9 | super(Expectation, self).__init__(eqn_config) 10 | self.strike = eqn_config.strike 11 | self.x_init = np.ones(self.dim) * eqn_config.x_init # initial value of x, the underlying 12 | self.sigma = eqn_config.sigma 13 | self.r = eqn_config.r 14 | self.useExplict = True #whether to use explict formula to evaluate dyanamics of x 15 | self.lamb = eqn_config.lamb 16 | self.aver_jump = eqn_config.aver_jump 17 | self.var_jump = eqn_config.var_jump 18 | self.u = eqn_config.u 19 | 20 | 21 | def sample(self, num_sample): 22 | 23 | # simulazione del Browniano 24 | 25 | dw_sample = normal.rvs(size=[num_sample, 26 | self.dim, 27 | self.num_time_interval]) * self.sqrt_delta_t 28 | 29 | if self.dim==1: 30 | dw_sample = np.expand_dims(dw_sample,axis=0) 31 | dw_sample = np.swapaxes(dw_sample,0,1) 32 | 33 | # simulazione dei salti 34 | 35 | eta = normal.rvs(mean=0.0 ,cov=1.0, size = [num_sample, self.dim, self.num_time_interval]) 36 | eta = np.reshape(eta,[num_sample, self.dim, self.num_time_interval]) 37 | Poisson = np.random.poisson(self.lamb * self.delta_t, [num_sample, self.dim , self.num_time_interval]) 38 | jumps = np.multiply(Poisson, self.aver_jump) + np.sqrt(self.var_jump)*np.multiply(np.sqrt(Poisson),eta) 39 | 40 | 41 | # traiettorie forward 42 | 43 | x_sample = np.zeros([num_sample, self.dim, self.num_time_interval + 1]) 44 | x_sample[:, :, 0] = np.ones([num_sample, self.dim]) * self.x_init 45 | 46 | if self.useExplict: 47 | factor = np.exp((self.r-(self.sigma**2)/2)*self.delta_t - self.lamb*(np.exp(self.aver_jump + 0.5*self.var_jump)-1)*self.delta_t) 48 | for i in range(self.num_time_interval): 49 | x_sample[:, :, i + 1] = (factor * np.exp(self.sigma * dw_sample[:, :, i]) * np.exp(jumps[:, :, i])) * x_sample[:, :, i] 50 | return x_sample, Poisson, jumps, dw_sample 51 | 52 | def f_tf(self, t, x, y, z): 53 | return 0 54 | 55 | def g_tf(self, t, x): 56 | return tf.math.exp(self.u*tf.math.log(x)) 57 | 58 | def getFsdeDiffusion(self, t, x): 59 | return 0 60 | 61 | 62 | class PricingForward(Equation): 63 | def __init__(self,eqn_config): 64 | super(PricingForward, self).__init__(eqn_config) 65 | self.strike = eqn_config.strike 66 | self.x_init = np.ones(self.dim) * eqn_config.x_init # initial value of x, the underlying 67 | self.sigma = eqn_config.sigma 68 | self.r = eqn_config.r 69 | self.useExplict = True #whether to use explict formula to evaluate dyanamics of x 70 | self.lamb = eqn_config.lamb 71 | self.aver_jump = eqn_config.aver_jump 72 | self.var_jump = eqn_config.var_jump 73 | self.u = eqn_config.u 74 | 75 | 76 | def sample(self, num_sample): 77 | 78 | # simulazione del Browniano 79 | 80 | dw_sample = normal.rvs(size=[num_sample, 81 | self.dim, 82 | self.num_time_interval]) * self.sqrt_delta_t 83 | 84 | if self.dim==1: 85 | dw_sample = np.expand_dims(dw_sample,axis=0) 86 | dw_sample = np.swapaxes(dw_sample,0,1) 87 | 88 | # simulazione dei salti 89 | 90 | eta = normal.rvs(mean=0.0 ,cov=1.0, size = [num_sample, self.dim, self.num_time_interval]) 91 | eta = np.reshape(eta,[num_sample, self.dim, self.num_time_interval]) 92 | Poisson = np.random.poisson(self.lamb * self.delta_t, [num_sample, self.dim , self.num_time_interval]) 93 | jumps = np.multiply(Poisson, self.aver_jump) + np.sqrt(self.var_jump)*np.multiply(np.sqrt(Poisson),eta) 94 | 95 | 96 | # traiettorie forward 97 | 98 | x_sample = np.zeros([num_sample, self.dim, self.num_time_interval + 1]) 99 | x_sample[:, :, 0] = np.ones([num_sample, self.dim]) * self.x_init 100 | 101 | if self.useExplict: 102 | factor = np.exp((self.r-(self.sigma**2)/2)*self.delta_t - self.lamb*(np.exp(self.aver_jump + 0.5*self.var_jump)-1)*self.delta_t) 103 | for i in range(self.num_time_interval): 104 | x_sample[:, :, i + 1] = (factor * np.exp(self.sigma * dw_sample[:, :, i]) * np.exp(jumps[:, :, i])) * x_sample[:, :, i] 105 | return x_sample, Poisson, jumps, dw_sample 106 | 107 | def f_tf(self, t, x, y, z): 108 | return -self.r * y 109 | 110 | def g_tf(self, t, x): 111 | return x - self.strike 112 | 113 | def getFsdeDiffusion(self, t, x): 114 | return self.sigma * x 115 | 116 | 117 | class CallOption(Equation): 118 | def __init__(self, eqn_config): 119 | super(CallOption, self).__init__(eqn_config) 120 | self.strike = eqn_config.strike 121 | self.x_init = np.ones(self.dim) * eqn_config.x_init 122 | self.sigma = eqn_config.sigma 123 | self.r = eqn_config.r 124 | self.lamb = eqn_config.lamb 125 | self.aver_jump = eqn_config.aver_jump 126 | self.var_jump = eqn_config.var_jump 127 | self.useExplict = True #whether to use explict formula to evaluate dyanamics of x 128 | 129 | def sample(self, num_sample): 130 | 131 | # simulazione del Browniano 132 | 133 | dw_sample = normal.rvs(size=[num_sample, 134 | self.dim, 135 | self.num_time_interval]) * self.sqrt_delta_t 136 | 137 | if self.dim==1: 138 | dw_sample = np.expand_dims(dw_sample,axis=0) 139 | dw_sample = np.swapaxes(dw_sample,0,1) 140 | 141 | # simulazione dei salti 142 | 143 | eta = normal.rvs(mean=0.0 ,cov=1.0, size = [num_sample, self.dim, self.num_time_interval]) 144 | eta = np.reshape(eta,[num_sample, self.dim, self.num_time_interval]) 145 | Poisson = np.random.poisson(self.lamb * self.delta_t, [num_sample, self.dim , self.num_time_interval]) 146 | jumps = np.multiply(Poisson, self.aver_jump) + np.sqrt(self.var_jump)*np.multiply(np.sqrt(Poisson),eta) 147 | 148 | 149 | # traiettorie forward 150 | 151 | x_sample = np.zeros([num_sample, self.dim, self.num_time_interval + 1]) 152 | x_sample[:, :, 0] = np.ones([num_sample, self.dim]) * self.x_init 153 | 154 | if self.useExplict: 155 | factor = np.exp((self.r-(self.sigma**2)/2)*self.delta_t - self.lamb*(np.exp(self.aver_jump + 0.5*self.var_jump)-1)*self.delta_t) 156 | for i in range(self.num_time_interval): 157 | x_sample[:, :, i + 1] = (factor * np.exp(self.sigma * dw_sample[:, :, i]) * np.exp(jumps[:, :, i])) * x_sample[:, :, i] 158 | return x_sample, Poisson, jumps, dw_sample 159 | 160 | def f_tf(self, t, x, y, z): 161 | return -self.r * y 162 | 163 | def g_tf(self, t, x): 164 | return tf.maximum( x - self.strike, 0) 165 | 166 | def getFsdeDiffusion(self, t, x): 167 | return self.sigma * x 168 | 169 | 170 | class BasketOption(Equation): 171 | def __init__(self, eqn_config): 172 | super(BasketOption, self).__init__(eqn_config) 173 | self.strike = eqn_config.strike 174 | self.x_init = np.ones(self.dim) * eqn_config.x_init 175 | self.sigma = eqn_config.sigma 176 | self.r = eqn_config.r 177 | self.lamb = eqn_config.lamb 178 | self.aver_jump = eqn_config.aver_jump 179 | self.var_jump = eqn_config.var_jump 180 | self.useExplict = True #whether to use explict formula to evaluate dyanamics of x 181 | 182 | def sample(self, num_sample): 183 | 184 | # simulazione del Browniano 185 | 186 | dw_sample = normal.rvs(size=[num_sample, 187 | self.dim, 188 | self.num_time_interval]) * self.sqrt_delta_t 189 | 190 | if self.dim==1: 191 | dw_sample = np.expand_dims(dw_sample,axis=0) 192 | dw_sample = np.swapaxes(dw_sample,0,1) 193 | 194 | # simulazione dei salti 195 | 196 | eta = normal.rvs(mean=0.0 ,cov=1.0, size = [num_sample, self.dim, self.num_time_interval]) 197 | eta = np.reshape(eta,[num_sample, self.dim, self.num_time_interval]) 198 | Poisson = np.random.poisson(self.lamb * self.delta_t, [num_sample, self.dim , self.num_time_interval]) 199 | jumps = np.multiply(Poisson, self.aver_jump) + np.sqrt(self.var_jump)*np.multiply(np.sqrt(Poisson),eta) 200 | 201 | 202 | # traiettorie forward 203 | 204 | x_sample = np.zeros([num_sample, self.dim, self.num_time_interval + 1]) 205 | x_sample[:, :, 0] = np.ones([num_sample, self.dim]) * self.x_init 206 | 207 | if self.useExplict: 208 | factor = np.exp((self.r-(self.sigma**2)/2)*self.delta_t - self.lamb*(np.exp(self.aver_jump + 0.5*self.var_jump)-1)*self.delta_t) 209 | for i in range(self.num_time_interval): 210 | x_sample[:, :, i + 1] = (factor * np.exp(self.sigma * dw_sample[:, :, i]) * np.exp(jumps[:, :, i])) * x_sample[:, :, i] 211 | return x_sample, Poisson, jumps, dw_sample 212 | 213 | def f_tf(self, t, x, y, z): 214 | return -self.r * y 215 | 216 | def g_tf(self, t, x): 217 | temp = tf.reduce_sum(x, 1,keepdims=True) 218 | #return tf.maximum(temp - self.dim * self.strike, 0) 219 | return tf.maximum(1 / self.dim * temp - self.strike, 0) 220 | 221 | 222 | def getFsdeDiffusion(self, t, x): 223 | return self.sigma * x 224 | 225 | 226 | 227 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/CGMY.py: -------------------------------------------------------------------------------- 1 | # %reset -f 2 | import numpy as np 3 | import scipy.special as sc 4 | from scipy.stats import multivariate_normal as normal 5 | from scipy.fft import fft, ifft 6 | import matplotlib.pyplot as plt 7 | import time 8 | # from scipy.stats import norm 9 | # import pandas as pd 10 | 11 | plt.rcParams['figure.dpi'] = 300 12 | 13 | C=0.1; G=3.5; M=10; Y=0.5; 14 | C=0.15 15 | G=13. 16 | M=14. 17 | Y=0.6 18 | eps = 0.00001 19 | 20 | a = 1 - Y 21 | sigmaEpsSq0 = C/M**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,M*eps)+C/G**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,G*eps) 22 | bep0=C*sc.gamma(a)*(sc.gammainc(a,M*eps) -1) 23 | lambdaep0=C*np.exp(-M*eps)*eps**(-Y)/Y +bep0*M/Y 24 | ben0=C*sc.gamma(a)*(sc.gammainc(a,G*eps) -1) 25 | lambdaen0=C*np.exp(-G*eps)*eps**(-Y)/Y +ben0*G/Y 26 | 27 | h = 0.01 28 | n = 100 29 | 30 | 31 | def_outside = False 32 | 33 | 34 | 35 | Npaths = int(1000) 36 | 37 | paths = np.zeros([Npaths,n]) 38 | # jumpSizes = np.zeros([Npaths,n]) 39 | # jumpIndicator = np.zeros([Npaths,n]) 40 | 41 | def CGMYpathSimulation(Npaths,h,n,epsilon, C,G,M,Y): 42 | if not def_outside: 43 | a = 1-Y 44 | sigmaEpsSq = C/M**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,M*eps)+C/G**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,G*eps) 45 | else: 46 | sigmaEpsSq = sigmaEpsSq0 47 | # print(sigmaEpsSq) 48 | dW = normal.rvs(size=[Npaths,n])*np.sqrt(h) 49 | diffu = np.cumsum(np.sqrt(sigmaEpsSq)*dW,axis=1) 50 | 51 | def CGMYPositiveOneSided(Npaths,h,n,eps, C,M,Y): 52 | a=1-Y 53 | #bep=C/(M**a)*sc.gamma(a)*(sc.gammainc(a,M*eps) -1) 54 | if not def_outside: 55 | bep=C*sc.gamma(a)*(sc.gammainc(a,M*eps) -1) 56 | 57 | # print(bep) 58 | lambdaep=C*np.exp(-M*eps)*eps**(-Y)/Y +bep*M/Y 59 | else: 60 | bep = bep0 61 | lambdaep = lambdaep0 62 | # print(lambdaep) 63 | DXep = np.zeros([Npaths,n]) 64 | jumpSizes = np.zeros([Npaths,n]) 65 | 66 | for k in range(0,Npaths): 67 | N=np.random.poisson(lambdaep) 68 | U=np.random.uniform(0,1,N) 69 | 70 | DJep = np.zeros(n) 71 | J = np.zeros(N) 72 | 73 | def CGMYJumpSize(eps,C,M,Y): 74 | W=np.random.uniform(0,1,1) 75 | V=np.random.uniform(0,1,1) 76 | X=eps*W**(-1/Y) 77 | T= np.exp(M*(X-eps)) 78 | while V*T>1: 79 | W=np.random.uniform(0,1,1) 80 | V=np.random.uniform(0,1,1) 81 | X=eps*W**(-1/Y) 82 | T= np.exp(M*(X-eps)) 83 | return X 84 | 85 | for j in range(0,N): 86 | J[j]= CGMYJumpSize(eps,C,M,Y) 87 | 88 | for i in range(0,n): 89 | DJep[i]=np.sum(J*(U>=i/n)*(U<(i+1)/n)) 90 | 91 | jumpSizes[k,:] = DJep 92 | DXep[k,:]=bep*h + DJep 93 | return DXep, jumpSizes 94 | 95 | def CGMYNegativeOneSided(Npaths,h,n,eps, C,M,Y): 96 | a=1-Y 97 | #bep=C/(M**a)*sc.gamma(a)*(sc.gammainc(a,M*eps) -1) 98 | 99 | if not def_outside: 100 | ben=C*sc.gamma(a)*(sc.gammainc(a,M*eps) -1) 101 | lambdaen=C*np.exp(-M*eps)*eps**(-Y)/Y +ben*M/Y 102 | else: 103 | ben = ben0 104 | lambdaen = lambdaen0 105 | 106 | # print(bep) 107 | # print(lambdaep) 108 | DXep = np.zeros([Npaths,n]) 109 | jumpSizes = np.zeros([Npaths,n]) 110 | 111 | for k in range(0,Npaths): 112 | N=np.random.poisson(lambdaen) 113 | U=np.random.uniform(0,1,N) 114 | 115 | DJep = np.zeros(n) 116 | J = np.zeros(N) 117 | 118 | def CGMYJumpSize(eps,C,M,Y): 119 | W=np.random.uniform(0,1,1) 120 | V=np.random.uniform(0,1,1) 121 | X=eps*W**(-1/Y) 122 | T= np.exp(M*(X-eps)) 123 | while V*T>1: 124 | W=np.random.uniform(0,1,1) 125 | V=np.random.uniform(0,1,1) 126 | X=eps*W**(-1/Y) 127 | T= np.exp(M*(X-eps)) 128 | return X 129 | 130 | for j in range(0,N): 131 | J[j]= CGMYJumpSize(eps,C,M,Y) 132 | 133 | for i in range(0,n): 134 | DJep[i]=np.sum(J*(U>=i/n)*(U<(i+1)/n)) 135 | 136 | jumpSizes[k,:] = DJep 137 | DXep[k,:]=ben*h + DJep 138 | return DXep, jumpSizes 139 | 140 | [DXpep, jumpSizesUp] = CGMYPositiveOneSided(Npaths,h,n,eps, C,M,Y) 141 | [DXnep, jumpSizesDown] = CGMYNegativeOneSided(Npaths,h,n,eps, C,G,Y) 142 | DXep=DXpep-DXnep+diffu 143 | jumpSizes = jumpSizesUp-jumpSizesDown 144 | jumpIndicator = np.zeros([Npaths,n]) 145 | jumpIndicator[jumpSizes!=0] = 1 146 | return DXep,DXpep, DXnep, jumpIndicator, jumpSizes, jumpSizesUp, jumpSizesDown, dW, diffu 147 | 148 | tic =time.perf_counter() 149 | [DXep,DXpep, DXnep, jumpIndicator, jumpSizes, jumpSizesUp, jumpSizesDown, dW, diffu] = CGMYpathSimulation(Npaths,h,n,eps, C,G,M,Y) 150 | Xep = np.cumsum(DXep,axis=1) 151 | toc = time.perf_counter() 152 | 153 | def cf_cgmy(u,T,r,d,C,G,M,Y): 154 | m = 0 155 | tmp = C*T*sc.gamma(-Y)*((M-1j*u)**Y-M**Y+(G+1j*u)**Y-G**Y) 156 | y = np.exp(1j*u*( (r-d+m)*T) + tmp) 157 | return y 158 | 159 | def getProbabilityDensity(n,T,r,d,C,G,M,Y): 160 | N = 2**n; 161 | eta = 0.1; 162 | lambda_ = (2*np.pi)/(N*eta) 163 | u = np.arange(0,(N)*eta,eta) 164 | b=(N*lambda_)/2 165 | psi = np.zeros([len(u)],dtype=np.complex_) 166 | 167 | for j in range(0,len(u)): 168 | psi[j] = cf_cgmy(u[j],T,r,d,C,G,M,Y) 169 | 170 | cf = psi*np.exp(1j*b*(np.transpose(u)))*eta 171 | 172 | jvec = np.transpose(range(1,N+1)) 173 | cf = (cf/3)*(3+(-1)**jvec-((jvec-1)==0)) 174 | ft = fft(cf,N) 175 | kv = np.arange(-b,(N)*lambda_-b,lambda_) 176 | kv = np.transpose(kv) 177 | 178 | density = np.real(ft/np.pi) 179 | return density, kv 180 | 181 | # True density via FFT 182 | Bound = 1.5 183 | [density, kv] = getProbabilityDensity(12,1,0,0,C,G,M,Y) 184 | I = np.where((kv >= -Bound) & (kv <= Bound)) 185 | 186 | 187 | fig = plt.figure() 188 | plt.plot(kv[I], density[I]) 189 | myhist = plt.hist(Xep[:,-1]*(np.abs(Xep[:,-1])1: 291 | W=np.random.uniform(0,1,1) 292 | V=np.random.uniform(0,1,1) 293 | X=eps*W**(-1/Y) 294 | T= np.exp(M*(X-eps)) 295 | return X 296 | 297 | for j in range(0,N): 298 | J[j]= CGMYJumpSize(eps,C,M,Y) 299 | 300 | for i in range(0,n): 301 | DJep[i]=np.sum(J*(U>=i/n)*(U<(i+1)/n)) 302 | 303 | jumpSizes[k,:,:] = DJep 304 | DXep[k,:,:]=bep*h + DJep 305 | return DXep, jumpSizes 306 | 307 | [DXpep, jumpSizesUp] = CGMYPositiveOneSided(Npaths,h,n,eps, C,M,Y) 308 | [DXnep, jumpSizesDown] = CGMYPositiveOneSided(Npaths,h,n,eps, C,G,Y) 309 | DXep=DXpep-DXnep+diffu 310 | jumpSizes = jumpSizesUp-jumpSizesDown 311 | jumpIndicator = np.zeros([Npaths,self.dim,n]) 312 | jumpIndicator[jumpSizes!=0] = 1 313 | 314 | m = -C*sc.gamma(-Y)*((M-1)**Y-M**Y+(G+1)**Y-G**Y) 315 | # Discretizzazione completa nel tempo 316 | x_sample = np.zeros([Npaths,self.dim,n+1]) 317 | x_sample[:,:,0]=np.ones([num_sample, self.dim]) * self.x_init 318 | for i in range(1,n+1): 319 | x_sample[:,:,i] = x_sample[:,:,i-1]*np.exp( (self.r-self.d+m)*h + DXep[:,:,i-1] ) 320 | 321 | return x_sample, jumpIndicator, jumpSizes, dW 322 | 323 | 324 | def f_tf(self, t, x, y, z): 325 | return -self.r * y 326 | 327 | def g_tf(self, t, x): 328 | return tf.maximum( x - self.strike, 0) 329 | 330 | def getFsdeDiffusion(self, t, x): 331 | eps = self.eps 332 | C = self.C 333 | G = self.G 334 | M = self.M 335 | Y = self.Y 336 | a = 1-Y 337 | sigmaEpsSq = C/M**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,M*eps)+C/G**(2-Y)*sc.gamma(a+1)*sc.gammainc(a+1,G*eps) 338 | # print(sigmaEpsSq) 339 | return sigmaEpsSq * x #il sigma deve essere il sigma calcolato con il CGMY cioè quello che in matlab è sigmaEpsSq dentro pathsimulation 340 | 341 | 342 | 343 | 344 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/PureJumpSolver.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import time 3 | import numpy as np 4 | import tensorflow as tf 5 | from tqdm import tqdm 6 | import tensorflow.keras.layers as layers 7 | from tensorflow.keras.layers import LeakyReLU 8 | from scipy.stats import multivariate_normal as normal 9 | import os 10 | DELTA_CLIP = 50.0 11 | 12 | 13 | class BSDESolver(object): 14 | """The fully connected neural network model.""" 15 | def __init__(self, config, bsde): 16 | self.eqn_config = config.eqn_config 17 | self.net_config = config.net_config 18 | self.bsde = bsde 19 | 20 | self.model = NonsharedModel(config, bsde) 21 | 22 | try: 23 | lr_schedule = config.net_config.lr_schedule 24 | except AttributeError: 25 | lr_schedule = tf.keras.optimizers.schedules.PiecewiseConstantDecay( 26 | self.net_config.lr_boundaries, self.net_config.lr_values) 27 | 28 | self.optimizer = tf.keras.optimizers.legacy.Adam(learning_rate=lr_schedule, epsilon=1e-8) 29 | 30 | def train(self): 31 | start_time = time.time() 32 | training_history = [] 33 | valid_data = self.bsde.sample(self.net_config.valid_size) 34 | 35 | # begin batch iteration 36 | for step in tqdm(range(self.net_config.num_iterations+1)): 37 | if step % self.net_config.logging_frequency == 0: 38 | loss = self.loss_fn(valid_data, training=False).numpy() 39 | y_init = self.model.simulate_path(valid_data)[0,0,0] # or y_init = self.model.subnet[0].call(valid_data[0][:,:,0],False)[0].numpy()[0] 40 | elapsed_time = time.time() - start_time 41 | training_history.append([step, loss, y_init, elapsed_time]) 42 | if self.net_config.verbose: 43 | print("step: %5u, loss: %.4e, Y0: %.4e, elapsed time: %3u" % ( 44 | step, loss, y_init, elapsed_time)) 45 | self.train_step(self.bsde.sample(self.net_config.batch_size)) 46 | return np.array(training_history) 47 | 48 | def loss_fn(self, inputs, training): 49 | 50 | x, Poisson, jumps, dw = inputs 51 | y_terminal, penalty = self.model(inputs, training) 52 | 53 | delta = y_terminal - self.bsde.g_tf(self.bsde.total_time, x[:, :, -1]) 54 | 55 | loss = tf.reduce_mean( delta**2 ) 56 | 57 | return 10 * loss + penalty 58 | 59 | def grad(self, inputs, training): 60 | with tf.GradientTape(persistent=True) as tape: 61 | loss = self.loss_fn(inputs, training) 62 | 63 | grad = tape.gradient(loss, self.model.trainable_variables) 64 | #clipped_gradients = [tf.clip_by_value(g, -5., 5.) for g in grad] 65 | del tape 66 | return grad 67 | 68 | @tf.function 69 | def train_step(self, train_data): 70 | grad = self.grad(train_data, training=True) 71 | self.optimizer.apply_gradients(zip(grad, self.model.trainable_variables)) 72 | 73 | 74 | class NonsharedModel(tf.keras.Model): 75 | def __init__(self, config, bsde): 76 | super(NonsharedModel, self).__init__() 77 | self.config = config 78 | self.eqn_config = config.eqn_config 79 | self.net_config = config.net_config 80 | self.bsde = bsde 81 | self.dim = bsde.dim 82 | self.subnet = [FeedForwardSubNet(config,1) for _ in range(self.bsde.num_time_interval)] 83 | self.subnetControl = [FeedForwardSubNetControl(config,bsde.dim) for _ in range(self.bsde.num_time_interval)] 84 | self.subnetCompensator = [FeedForwardSubNet(config,1) for _ in range(self.bsde.num_time_interval)] 85 | self.y_init = tf.Variable(np.random.uniform(low = self.net_config.y_init_range[0], high = self.net_config.y_init_range[1], size=[1]),dtype=self.net_config.dtype) 86 | 87 | 88 | def save_model(self, path_dir = 'Model_LR'): 89 | 90 | try: 91 | os.mkdir(path_dir) 92 | 93 | nets = self.subnet 94 | netsControl = self.subnetControl 95 | netsComp = self.subnetCompensator 96 | 97 | for i in range(self.bsde.num_time_interval-1): 98 | path = path_dir + '/net_{}'.format(i) 99 | pathComp = path_dir + '/netComp_{}'.format(i) 100 | model = nets[i] 101 | model.save(path) 102 | modelComp = netsComp[i] 103 | modelComp.save(pathComp) 104 | 105 | print('Directory ', '\033[1m' + path_dir + '\033[0m', ' created') 106 | 107 | except OSError: 108 | print('Directory already existing: try another name') 109 | 110 | 111 | def load_model(self, path_dir = 'Model_LR'): 112 | 113 | nets = [] 114 | netsControl = [] 115 | netsComp = [] 116 | for i in range(self.bsde.num_time_interval-1): 117 | path = path_dir + '/net_{}'.format(i) 118 | model = tf.keras.models.load_model(path) 119 | nets.append(model) 120 | 121 | pathControl = path_dir + '/netControl_{}'.format(i) 122 | modelControl = tf.keras.models.load_model(pathControl) 123 | netsControl.append(model) 124 | 125 | 126 | pathComp = path_dir + '/netComp_{}'.format(i) 127 | modelComp = tf.keras.models.load_model(pathComp) 128 | netsComp.append(modelComp) 129 | 130 | self.subnet = nets 131 | self.subnetCompensator = netsComp 132 | self.subnetControl = netsControl 133 | 134 | 135 | @tf.function 136 | def call(self, inputs, training): 137 | print('Training!') 138 | x, Poisson, jumps, dw = inputs 139 | time_stamp = np.arange(0, self.eqn_config.num_time_interval) * self.bsde.delta_t 140 | all_one_vec = tf.ones(shape=tf.stack([tf.shape(Poisson)[0], 1]), dtype=self.net_config.dtype) 141 | 142 | 143 | y = all_one_vec * self.y_init 144 | 145 | #y = all_one_vec * self.subnet[0].call(all_one_vec * self.bsde.x_init,training) 146 | 147 | penalty = 0.0 148 | one_net = False 149 | for t in range(0, self.bsde.num_time_interval): 150 | if one_net: 151 | batch_size = tf.shape(x)[0] 152 | t_vector = tf.cast(tf.fill([batch_size, 1], self.bsde.delta_t * t), dtype=x.dtype) 153 | 154 | input_concat_z = tf.concat([t_vector, x[:,:,t]], axis=1) 155 | z = self.subnetControl[0](input_concat_z, training=True)# * self.bsde.getFsdeDiffusion(t,x[:, :, t])/ self.bsde.dim 156 | 157 | #input_concat_jump = tf.concat([t_vector, x[:,:,t], x[:, :, t ] * tf.math.exp(jumps[:, :, t])], axis=1) 158 | input_concat_jump = tf.concat([t_vector, x[:,:,t]], axis=1) 159 | f_Jump = self.subnetCompensator[0].call(input_concat_jump, training=True) * ( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t ] ) 160 | 161 | input_concat_comp = tf.concat([t_vector, x[:,:,t]], axis=1) 162 | f_compensator = self.subnet[0].call(input_concat_comp, training=True) 163 | 164 | ### 165 | #f_Jump = self.subnetCompensator[0].call(x[:,:,t],training=True) * tf.reduce_sum( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t ], axis=1, keepdims=True) 166 | #f_compensator = self.subnet[0].call(x[:, :, t],training=True) 167 | ### 168 | else: 169 | z = self.subnetControl[t](x[:, :, t], training=True) #* self.bsde.getFsdeDiffusion(t,x[:, :, t])/ self.bsde.dim 170 | 171 | input_concat = tf.concat([x[:,:,t], x[:,:,t] * tf.math.exp(jumps[:,:,t])], axis=1) 172 | f_Jump = self.subnetCompensator[t].call(input_concat,training=True) * ( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t ] ) 173 | f_compensator = self.subnet[t].call(x[:, :, t],training=True) 174 | 175 | compensatedJump = f_Jump - f_compensator * self.bsde.delta_t 176 | penalty += ( tf.reduce_mean( compensatedJump ) )**2 177 | 178 | 179 | y = y - self.bsde.delta_t * (self.bsde.f_tf(time_stamp[t], x[:, :, t], y, z)) + compensatedJump + \ 180 | tf.reduce_sum(z * self.bsde.getFsdeDiffusion(time_stamp[t],x[:, :, t]) * dw[:, :, t], 1, keepdims=True) 181 | 182 | 183 | return y, penalty 184 | 185 | 186 | @tf.function 187 | def predict_step(self, data): 188 | print('Predicting!') 189 | x, Poisson, jumps, dw = data[0] 190 | 191 | time_stamp = np.arange(0, self.eqn_config.num_time_interval) * self.bsde.delta_t 192 | all_one_vec = tf.ones(shape=tf.stack([tf.shape(Poisson)[0], 1]), dtype=self.net_config.dtype) 193 | 194 | 195 | y = all_one_vec * self.y_init 196 | #y = all_one_vec * self.subnet[0].call(all_one_vec * self.bsde.x_init,False) 197 | 198 | 199 | history = tf.TensorArray(self.net_config.dtype,size=self.bsde.num_time_interval+1) 200 | history = history.write(0,y) 201 | 202 | one_net = False 203 | for t in range(0, self.bsde.num_time_interval): 204 | 205 | if one_net: 206 | batch_size = tf.shape(x)[0] 207 | 208 | t_vector = tf.cast(tf.fill([batch_size, 1], self.bsde.delta_t * t), dtype=x.dtype) 209 | 210 | input_concat_z = tf.concat([t_vector, x[:,:,t]], axis=1) 211 | z = self.subnetControl[0](input_concat_z, training=False) # * self.bsde.getFsdeDiffusion(t,x[:, :, t])/ self.bsde.dim 212 | 213 | #input_concat_jump = tf.concat([t_vector, x[:,:,t], x[:, :, t ] * tf.math.exp(jumps[:, :, t])], axis=1) 214 | input_concat_jump = tf.concat([t_vector, x[:,:,t]], axis=1) 215 | f_Jump = self.subnetCompensator[0].call(input_concat_jump, training=False) * ( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t ] ) 216 | 217 | input_concat_comp = tf.concat([t_vector, x[:,:,t]], axis=1) 218 | f_compensator = self.subnet[0].call(input_concat_comp, training=False) 219 | 220 | ### 221 | #f_Jump = self.subnetCompensator[0].call(x[:,:,t],training=False) * tf.reduce_sum( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t], axis=1, keepdims=True) 222 | #f_compensator = self.subnet[0].call(x[:, :, t],training=False) 223 | ### 224 | else: 225 | z = self.subnetControl[t](x[:, :, t], training=False) #* self.bsde.getFsdeDiffusion(t,x[:, :, t])/ self.bsde.dim 226 | input_concat = tf.concat([x[:,:,t], x[:,:,t] * tf.math.exp(jumps[:,:,t])], axis=1) 227 | f_Jump = self.subnetCompensator[t].call(input_concat,training=True) * ( x[:, :, t ] * tf.math.exp(jumps[:, :, t]) - x[:, :, t ] ) 228 | f_compensator = self.subnet[t].call(x[:, :, t],training=False) 229 | 230 | compensatedJump = f_Jump - f_compensator * self.bsde.delta_t 231 | 232 | y = y - self.bsde.delta_t * ( 233 | self.bsde.f_tf(time_stamp[t], x[:, :, t], y, z)) + compensatedJump + \ 234 | tf.reduce_sum(z * self.bsde.getFsdeDiffusion(time_stamp[t],x[:, :, t]) * dw[:, :, t], 1, keepdims=True) 235 | 236 | 237 | history = history.write(t+1,y) 238 | 239 | history = tf.transpose(history.stack(),perm=[1,2,0]) 240 | # return Poisson, jumps, x, history, dw 241 | return x, Poisson, jumps, dw, history 242 | 243 | def simulate_path(self,num_sample): 244 | # return self.predict(num_sample)[3] 245 | return self.predict(num_sample)[4] 246 | 247 | 248 | class FeedForwardSubNet(tf.keras.Model): 249 | def __init__(self, config,dim): 250 | super(FeedForwardSubNet, self).__init__() 251 | num_hiddens = config.net_config.num_hiddens 252 | self.bn_layers = [ 253 | tf.keras.layers.BatchNormalization( 254 | momentum=0.99, 255 | epsilon=1e-6, 256 | beta_initializer=tf.random_normal_initializer(0.0, stddev=0.1), 257 | gamma_initializer=tf.random_uniform_initializer(0., 0.5) 258 | ) 259 | for _ in range(len(num_hiddens) + 2)] 260 | self.dense_layers = [tf.keras.layers.Dense(num_hiddens[i], 261 | use_bias=True, 262 | activation=None,) 263 | for i in range(len(num_hiddens))] 264 | self.dense_layers.append(tf.keras.layers.Dense(dim, activation=None)) 265 | 266 | def call(self, x, training): 267 | """structure: bn -> (dense -> bn -> relu) * len(num_hiddens) -> dense """ 268 | x = self.bn_layers[0](x, training) 269 | for i in range(len(self.dense_layers) - 1): 270 | x = self.dense_layers[i](x) 271 | x = self.bn_layers[i+1](x, training) 272 | x = tf.nn.relu(x) 273 | #x = tf.nn.sigmoid(x) 274 | #x = tf.nn.tanh(x) 275 | x = self.dense_layers[-1](x) 276 | 277 | 278 | """ 279 | Questa somma serve per ridurre la dimensione da d a 1 ora la rete 280 | rappresenta una funzione da Rd a R. 281 | """ 282 | #tf.math.reduce_sum(x,0) 283 | return x 284 | 285 | def grad(self, x): 286 | x_tensor = tf.convert_to_tensor(x, dtype=tf.float64) 287 | with tf.GradientTape(watch_accessed_variables=True) as t: 288 | t.watch(x_tensor) 289 | out = self.call(x_tensor,training=False) 290 | grad = t.gradient(out,x_tensor) 291 | del t 292 | return grad 293 | 294 | class FeedForwardSubNetControl(tf.keras.Model): 295 | def __init__(self, config,dim): 296 | super(FeedForwardSubNetControl, self).__init__() 297 | num_hiddens = config.net_config.num_hiddens 298 | self.bn_layers = [ 299 | tf.keras.layers.BatchNormalization( 300 | momentum=0.99, 301 | epsilon=1e-6, 302 | beta_initializer=tf.random_normal_initializer(0.0, stddev=0.1), 303 | gamma_initializer=tf.random_uniform_initializer(0., 0.5) 304 | ) 305 | for _ in range(len(num_hiddens) + 2)] 306 | self.dense_layers = [tf.keras.layers.Dense(num_hiddens[i], 307 | use_bias=True, 308 | activation=None,) 309 | for i in range(len(num_hiddens))] 310 | self.dense_layers.append(tf.keras.layers.Dense(dim, activation=None)) 311 | 312 | def call(self, x, training): 313 | """structure: bn -> (dense -> bn -> relu) * len(num_hiddens) -> dense """ 314 | x = self.bn_layers[0](x, training) 315 | for i in range(len(self.dense_layers) - 1): 316 | x = self.dense_layers[i](x) 317 | x = self.bn_layers[i+1](x, training) 318 | x = tf.nn.relu(x) 319 | #x = tf.nn.sigmoid(x) 320 | #x = tf.nn.tanh(x) 321 | x = self.dense_layers[-1](x) 322 | 323 | return x 324 | 325 | def grad(self, x): 326 | x_tensor = tf.convert_to_tensor(x, dtype=tf.float64) 327 | with tf.GradientTape(watch_accessed_variables=True) as t: 328 | t.watch(x_tensor) 329 | out = self.call(x_tensor,training=False) 330 | grad = t.gradient(out,x_tensor) 331 | del t 332 | return grad 333 | 334 | -------------------------------------------------------------------------------- /Deep-Solver-Jumps-master-github/script_call_option.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | import tensorflow as tf 5 | from PureJumpSolver import BSDESolver 6 | import PureJumpEquation as eqn 7 | import munch 8 | from scipy.stats import norm 9 | import pandas as pd 10 | import sys 11 | import os 12 | import itertools 13 | from scipy.stats import multivariate_normal as normal 14 | from scipy.optimize import minimize_scalar 15 | N = norm.cdf 16 | 17 | 18 | # path: C:\Users\mrcpa\Dropbox\Documenti\Marco\UNIVERSITA\RtdA_Verona\Ricerca\Deep Learning\20240627_Deep-Solver-master PureJump_ez_MP 19 | 20 | plt.rcParams['figure.dpi'] = 300 21 | 22 | 23 | 24 | if __name__ == "__main__": 25 | 26 | ## Specify if we want to train the model (and save it), or to load it 27 | train_model = True # If this is False, the next is not checked 28 | save_model = True 29 | 30 | dim = 1 #dimension of brownian motion 31 | P = 2**16 #number of outer Monte Carlo Loops 32 | batch_size = 2**5 #2048*8 33 | total_time = 1. 34 | num_time_interval = 40 35 | strike = 0.9 36 | lamb = 0.3 37 | r = 0.05 38 | sigma = 0.25 39 | aver_jump = 0.5 40 | var_jump = 0.25**2 41 | x_init = 1.0 42 | 43 | ## Specify the name of the directory where model and simulations lie 44 | path_dir = 'LocalRisk{}points'.format(num_time_interval) 45 | 46 | config = { 47 | "eqn_config": { 48 | "_comment": "a call contract", 49 | "eqn_name": "CallOption", 50 | "total_time": total_time, 51 | "dim": dim, 52 | "num_time_interval": num_time_interval, 53 | "strike":strike, 54 | "r":r, 55 | "sigma":sigma, 56 | "lamb":lamb, 57 | "aver_jump":aver_jump, 58 | "var_jump":var_jump, 59 | "x_init":x_init, 60 | 61 | }, 62 | "net_config": { 63 | "num_hiddens": [15, 15], 64 | "lr_values": [7.5e-2, 5e-2, 5e-3, 5e-4, 1e-4], 65 | "lr_boundaries": [1000,4000,6000, 15000], # "lr_boundaries": [1000,4000,10000, 15000], 66 | "num_iterations": 10000, 67 | "batch_size": batch_size, 68 | "valid_size": 256, 69 | "logging_frequency": 100, 70 | "dtype": "float64", 71 | "y_init_range": [0.24, 0.4], 72 | "verbose": True 73 | } 74 | } 75 | 76 | 77 | 78 | ''' 79 | "net_config": { 80 | "num_hiddens": [dim+30, dim+30], 81 | "lr_values": [5e-2, 5e-3, 5e-4, 1e-4], 82 | "lr_boundaries": [5000, 10000, 15000], 83 | "num_iterations": 20000, 84 | "batch_size": batch_size, 85 | "valid_size": 256, 86 | "logging_frequency": 100, 87 | "dtype": "float64", 88 | "y_init_range": [0.24, 0.4], 89 | "verbose": True 90 | ''' 91 | config = munch.munchify(config) 92 | bsde = getattr(eqn, config.eqn_config.eqn_name)(config.eqn_config) 93 | tf.keras.backend.set_floatx(config.net_config.dtype) 94 | 95 | samples = bsde.sample(P) 96 | stock = samples[0] 97 | mcprice = np.exp(-r* total_time)*np.average(np.maximum(stock[:,0,-1] - strike,0)) 98 | np.disp(mcprice) 99 | 100 | #apply algorithm 1 101 | bsde_solver = BSDESolver(config, bsde) 102 | 103 | training_history = bsde_solver.train() 104 | simulations = bsde_solver.model.simulate_path(samples) 105 | 106 | 107 | # if train_model: 108 | 109 | # ## Train the model 110 | # training_history = bsde_solver.train() 111 | # simulations = bsde_solver.model.simulate_path(samples) 112 | # # aba = bsde_solver.model.predict_step(samples) 113 | 114 | # if save_model: 115 | 116 | # # Create the directory 117 | # try: 118 | # os.mkdir(path_dir) 119 | # print('Directory ', '\033[1m' + path_dir + '\033[0m', ' created') 120 | 121 | # except OSError: 122 | # print('Directory ', '\033[1m' + path_dir + '\033[0m', ' already existing: try another name') 123 | 124 | # ## Save 125 | # path = path_dir + '/Model1_MV{}points'.format(num_time_interval) 126 | # bsde_solver.model.save_model(path) 127 | # np.save(path_dir + '/training_history_{}.npy'.format(num_time_interval), training_history) 128 | # else: 129 | 130 | # ## Load 131 | # path = path_dir + '/Model1_MV{}points'.format(num_time_interval) 132 | # bsde_solver.model.load_model(path) 133 | # training_history = np.load(path_dir + '/training_history_{}.npy'.format(num_time_interval)) 134 | 135 | 136 | ####### SEMI-EXPLICIT SOLUTION 137 | 138 | 139 | def BS_CALL(S, K, T, r, sigma): 140 | d1 = (np.log(S/K) + (r + sigma**2/2)*T) / (sigma*np.sqrt(T)) 141 | d2 = d1 - sigma * np.sqrt(T) 142 | return S * N(d1) - K * np.exp(-r*T)* N(d2) 143 | 144 | def merton_jump_call(S, K, T, r, sigma, m , v, lam): 145 | p = 0 146 | for k in range(100): 147 | r_k = r - lam*(m-1) + (k*np.log(m) ) / T 148 | sigma_k = np.sqrt( sigma**2 + (k* v** 2) / T) 149 | k_fact = np.math.factorial(k) 150 | p += (np.exp(-m*lam*T) * (m*lam*T)**k / (k_fact)) * BS_CALL(S, K, T, r_k, sigma_k) 151 | 152 | return p 153 | 154 | ########### 155 | 156 | 157 | # Simulate the BSDE after training - MtM scenarios 158 | samples = bsde.sample(P) 159 | simulations = bsde_solver.model.simulate_path(samples) # Y 160 | 161 | 162 | #history_pred = bsde_solver.model.predict_step(samples) 163 | num_paths = 4 164 | price_exact = np.zeros((num_paths,num_time_interval+1)) 165 | price_exact[:,num_time_interval] = np.maximum(samples[0][0:num_paths,0,num_time_interval]-strike,0) # formula semi-analitica 166 | price_approx = np.zeros((num_paths,num_time_interval)) # NN_n (S_n) 167 | 168 | delta_t = total_time / num_time_interval 169 | std_jump = np.sqrt(var_jump) 170 | 171 | ''' 172 | fig = plt.figure() 173 | ax = plt.gca() 174 | 175 | from matplotlib.pyplot import cm 176 | color = cm.rainbow(np.linspace(0, 1, num_paths)) 177 | 178 | for omega in range(0,num_paths): 179 | for time in range(0,num_time_interval): 180 | assetprice = samples[0][omega,0,time] 181 | #price_approx[omega,time] = bsde_solver.model.subnet[time].call(np.reshape(assetprice, [1, 1]),training=False) 182 | price_exact[omega,time] = merton_jump_call(assetprice, strike, total_time-time*delta_t, r, sigma, aver_jump , std_jump, lamb) 183 | #price_exact[omega,time] = merton_jump_call(assetprice, strike, total_time-time*delta_t, r, sigma, np.exp(aver_jump + std_jump**2/2) , std_jump, lamb) 184 | 185 | #color = next(ax._get_lines.prop_cycler)['color'] 186 | cc = color[omega] 187 | plt.plot(price_exact[omega,:], '--',color = cc) 188 | plt.plot(simulations[omega,0,:], color = cc) 189 | #plt.plot(price_approx[omega,:], color = color) 190 | 191 | 192 | fig = plt.figure() 193 | for omega in range(0,num_paths): 194 | plt.plot(samples[0][omega,0,:]) 195 | ''' 196 | 197 | 198 | #%% 199 | # Create the plot with a specific figure size 200 | NN = np.int(15000/100) 201 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 202 | 203 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 204 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Analytic)', linewidth=2) 205 | 206 | # Add labels and title 207 | plt.xlabel('Number of iterations') 208 | plt.ylabel('Y') 209 | plt.legend() 210 | plt.grid() 211 | plt.show() 212 | 213 | plt.figure(figsize=(4, 6)) # Adjust the dimensions to match the aspect ratio of your image 214 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 215 | 216 | # Add labels and title 217 | plt.xlabel('Number of batch iterations') 218 | plt.yscale('log') 219 | plt.legend() 220 | plt.grid() 221 | 222 | # Show the plot 223 | plt.figure() 224 | plt.plot(training_history[:NN,0], training_history[:NN,2], label=f'$Y_0$ (Approx.)') 225 | plt.plot(training_history[:NN,0], mcprice * np.ones(len(training_history[:NN,0])), '--', color='red', label=f'$Y_0$ (Analytic)', linewidth=2) 226 | 227 | # Add labels and title 228 | plt.xlabel('Number of iterations') 229 | plt.ylabel('Y') 230 | plt.legend() 231 | plt.grid() 232 | 233 | plt.figure() 234 | plt.plot(training_history[:NN,0], training_history[:NN,1], label='Loss value') 235 | 236 | # Add labels and title 237 | plt.xlabel('Number of batch iterations') 238 | plt.yscale('log') 239 | plt.legend() 240 | plt.grid() 241 | plt.show() 242 | 243 | 244 | #%% 245 | import random 246 | plt.rcParams['figure.dpi'] = 100 247 | P = 2**16 248 | # Simulate the BSDE after training - MtM scenarios 249 | samples = bsde.sample(P) 250 | pay_off = np.maximum(samples[0][:,0,-1] - strike ,0) 251 | simulations = bsde_solver.model.simulate_path(samples) # Y 252 | 253 | #history_pred = bsde_solver.model.predict_step(samples) 254 | 255 | color = ['blue', 'red', 'green', 'purple', 'orange', 'black', 'grey', 'magenta', 'cyan'] 256 | 257 | price_exact = np.zeros((P,num_time_interval+1)) 258 | price_exact[:,num_time_interval] = np.maximum(samples[0][:,0,num_time_interval]-strike,0) # formula semi-analitica 259 | f_compensator = np.zeros((P,num_time_interval)) # NN_n (S_n) 260 | NN_jump = np.zeros((P,num_time_interval)) 261 | f_jump = np.zeros((P,num_time_interval)) 262 | Z = np.zeros((P,num_time_interval)) 263 | one_net = False 264 | for time in range(0, num_time_interval): 265 | assetprice = samples[0][:, 0, time] 266 | jumped_assetprice = samples[0][:, 0, time] * np.exp(samples[2][:,0,time]) 267 | 268 | #price_approx[omega, time] = bsde_solver.model.subnet[time].call(np.reshape(assetprice, [1, 1]), training=False) 269 | #price_exact[omega, time] = merton_jump_call(assetprice, strike, total_time - time * delta_t, r, sigma, aver_jump, std_jump, lamb) 270 | price_exact[:,time] = merton_jump_call(assetprice, strike, total_time-time*delta_t, r, sigma, np.exp(aver_jump + std_jump**2/2) , std_jump, lamb) 271 | if one_net: 272 | time_vector = np.ones(P)*time 273 | input_comp = np.array([time_vector, assetprice], dtype = np.float64).T 274 | f_compensator[:, time] = bsde_solver.model.subnet[0](input_comp, training=False)[:,0] 275 | 276 | #input_jump = np.reshape(np.array([time, assetprice, jumped_assetprice], dtype=np.float64), (P, 3)) 277 | input_jump = np.array([time_vector, assetprice], dtype = np.float64).T 278 | NN_jump[:, time] = bsde_solver.model.subnetCompensator[0](input_jump,training=False)[:,0] 279 | 280 | input_Z = np.array([time_vector, assetprice], dtype = np.float64).T 281 | Z[:, time] = bsde_solver.model.subnetControl[0](input_Z, training=False)[:,0] 282 | 283 | else: 284 | f_compensator[:, time] = bsde_solver.model.subnet[0](np.reshape([samples[0][:, 0, time]], [P, 1]), training=False)[:,0] 285 | 286 | NN_jump[:, time] = bsde_solver.model.subnetCompensator[time](np.reshape([samples[0][:, 0, time], samples[0][:, 0, time]*np.exp(samples[2][:,0,time])], [P, 2]),training=False)[:,0] 287 | #NN_jump[:, time] = bsde_solver.model.subnetCompensator[0](np.reshape([samples[0][:, 0, time]], [P, 1]),training=False)[:,0] 288 | Z[:, time] = bsde_solver.model.subnetControl[time](np.reshape([assetprice], [P, 1]), training=False)[:,0] 289 | f_jump[:, time] = NN_jump[:, time] * (jumped_assetprice - assetprice) 290 | 291 | compensated_jumps = f_jump - f_compensator * delta_t 292 | MSE_t = np.mean((price_exact-simulations[:,0,:])**2, 0) 293 | 294 | 295 | #%% 296 | n = random.randint(0, P) - num_paths 297 | #n = 0 298 | num_paths = 5 299 | t = np.linspace(0, 1, num_time_interval+1) 300 | pay_off = np.maximum(samples[0][:, 0, -1] - strike, 0) 301 | terminal_error = simulations[:, 0, -1] - pay_off 302 | sorted_indices = np.argsort(np.abs(terminal_error)) 303 | top_five_indices = sorted_indices[-5:] 304 | top_five_indices_desc = sorted_indices[-1:-6:-1] 305 | 306 | #n = top_five_indices[0] 307 | ''' 308 | for omega in range(n,n+num_paths): 309 | plt.plot(price_exact[omega, :], color=color[omega-n], label='Y (exact)' if omega == 0 else "") 310 | plt.plot(time+1, pay_off[omega], 'x', color = color[omega-n]) 311 | plt.plot(simulations[omega, 0, :],'--', color=color[omega-n], label='Y (EM-approx)' if omega == 0 else "") 312 | 313 | # Ensure legend is added only once per figure 314 | if omega-n == 0: 315 | plt.legend() 316 | plt.grid() 317 | ''' 318 | 319 | plt.plot(np.mean(samples[0][:,0,:],0)) 320 | plt.plot(np.mean(simulations[:,0,:],0)) 321 | 322 | plt.figure() 323 | for omega in range(5): 324 | plt.plot(t, simulations[top_five_indices[omega], 0, :], color='red') 325 | plt.plot(t, price_exact[top_five_indices[omega], :], '--', color='black') 326 | plt.plot(t[-1], pay_off[top_five_indices[omega]], 'x', color = 'black') 327 | 328 | plt.grid() 329 | plt.legend(['Y (Approx.)','Y (Analytic)']) 330 | plt.figure() 331 | 332 | for omega in range(n,n+num_paths): 333 | plt.plot(t, simulations[omega, 0, :], color='red') 334 | plt.plot(t, price_exact[omega, :], '--', color='black') 335 | plt.plot(t[-1], pay_off[omega], 'x', color = 'black') 336 | 337 | plt.grid() 338 | plt.legend(['Y (Approx.)','Y (Analytic)']) 339 | 340 | 341 | #%% 342 | 343 | plt.plot(f_compensator[n,:]) 344 | plt.plot(f_jump[n,:]) 345 | plt.plot(Z[n,:],':') 346 | plt.plot(price_exact[n,:],'--') 347 | plt.plot(samples[0][n,0,:], '.-') 348 | plt.plot(samples[3][n,0,:], 'o-') 349 | #plt.plot(simulations[n,0,:]) 350 | 351 | 352 | 353 | #%% 354 | n = random.randint(0, P)-1 355 | y = np.zeros((P,num_time_interval+1)) 356 | y[:,0] = simulations[n,0,0] 357 | #k = np.argmax(np.abs(f_jump[n,:])) 358 | for i in range(num_time_interval): 359 | y[:,i+1] = y[:,i] + delta_t*r*y[:,i] + compensated_jumps[:,i] + Z[:,i]*sigma*samples[0][:,0,i]*samples[3][:,0,i] 360 | 361 | 362 | plt.plot(samples[0][n,0,:]) 363 | plt.figure() 364 | #plt.plot(y[n,:], '.-') 365 | plt.plot(price_exact[n,:], 'k') 366 | #plt.plot(simulations[n,0,:k+2],'--') 367 | plt.plot(simulations[n,0,:],'--') 368 | plt.plot(f_jump[n,:],'.') 369 | 370 | 371 | 372 | 373 | 374 | 375 | #%% 376 | import random 377 | 378 | # Identifying different jump indices 379 | index_0_jumps = np.argwhere(np.sum(samples[1][:, 0, :], 1) == 0)[:, 0] 380 | index_jumps = np.argwhere(np.sum(samples[1][:, 0, :], 1) > 0)[:, 0] 381 | index_1_jump = np.argwhere(np.sum(samples[1][:, 0, :], 1) == 1)[:, 0] 382 | index_2_jumps = np.argwhere(np.sum(samples[1][:, 0, :], 1) == 2)[:, 0] 383 | index_3_jumps = np.argwhere(np.sum(samples[1][:, 0, :], 1) == 3)[:, 0] 384 | 385 | # Calculate payoff and terminal error 386 | pay_off = np.maximum(samples[0][:, 0, -1] - strike, 0) 387 | terminal_error = simulations[:, 0, -1] - pay_off 388 | terminal_error_y = y[:, -1] - pay_off 389 | 390 | 391 | # Plot 1: Histogram of terminal errors for all samples 392 | plt.hist(terminal_error, 50) 393 | plt.title('Histogram of Terminal Errors (All Samples)') 394 | plt.xlabel('Terminal Error') 395 | plt.ylabel('Frequency') 396 | 397 | # Plot 2: Histogram for cases with no jumps 398 | plt.figure() 399 | plt.hist(terminal_error[index_0_jumps], 50) 400 | plt.title('Histogram of Terminal Errors (No Jumps)') 401 | plt.xlabel('Terminal Error') 402 | plt.ylabel('Frequency') 403 | 404 | # Plot 3: Histogram for cases with 1 jump 405 | plt.figure() 406 | plt.hist(terminal_error[index_1_jump], 50) 407 | plt.title('Histogram of Terminal Errors (1 Jump)') 408 | plt.xlabel('Terminal Error') 409 | plt.ylabel('Frequency') 410 | 411 | # Plot 4: Histogram for cases with 2 jumps 412 | plt.figure() 413 | plt.hist(terminal_error[index_2_jumps], 50) 414 | plt.title('Histogram of Terminal Errors (2 Jumps)') 415 | plt.xlabel('Terminal Error') 416 | plt.ylabel('Frequency') 417 | 418 | # Plot 5: Histogram for cases with 3 jumps 419 | plt.figure() 420 | plt.hist(terminal_error[index_3_jumps], 50) 421 | plt.title('Histogram of Terminal Errors (3 Jumps)') 422 | plt.xlabel('Terminal Error') 423 | plt.ylabel('Frequency') 424 | 425 | plt.show() # Ensure all plots are displayed 426 | ''' 427 | # Plot 1: Histogram of terminal errors for all samples 428 | plt.hist(terminal_error_y, 50) 429 | plt.title('Histogram of Terminal Errors (All Samples)') 430 | plt.xlabel('Terminal Error') 431 | plt.ylabel('Frequency') 432 | 433 | # Plot 2: Histogram for cases with no jumps 434 | plt.figure() 435 | plt.hist(terminal_error_y[index_0_jumps], 50) 436 | plt.title('Histogram of Terminal Errors (No Jumps)') 437 | plt.xlabel('Terminal Error') 438 | plt.ylabel('Frequency') 439 | 440 | # Plot 3: Histogram for cases with 1 jump 441 | plt.figure() 442 | plt.hist(terminal_error_y[index_1_jump], 50) 443 | plt.title('Histogram of Terminal Errors (1 Jump)') 444 | plt.xlabel('Terminal Error') 445 | plt.ylabel('Frequency') 446 | 447 | # Plot 4: Histogram for cases with 2 jumps 448 | plt.figure() 449 | plt.hist(terminal_error_y[index_2_jumps], 50) 450 | plt.title('Histogram of Terminal Errors (2 Jumps)') 451 | plt.xlabel('Terminal Error') 452 | plt.ylabel('Frequency') 453 | 454 | # Plot 5: Histogram for cases with 3 jumps 455 | plt.figure() 456 | plt.hist(terminal_error_y[index_3_jumps], 50) 457 | plt.title('Histogram of Terminal Errors (3 Jumps)') 458 | plt.xlabel('Terminal Error') 459 | plt.ylabel('Frequency') 460 | 461 | plt.show() # Ensure all plots are displayed 462 | ''' 463 | n = random.randint(0, P) 464 | 465 | plt.plot(NN_jump[n:n+5,:].T) 466 | plt.grid() 467 | 468 | plt.figure() 469 | plt.plot(f_compensator[n:n+5,:].T) 470 | plt.grid() 471 | 472 | plt.figure() 473 | plt.plot(f_jump[n:n+5,:].T) 474 | plt.grid() 475 | print('E|Y_N-g(X_N)|^2: ', np.mean(terminal_error**2)) 476 | print('E[compensated_jumps]^2: ', np.sum(np.mean(compensated_jumps,0)**2)) 477 | print('loss: ', 10*np.mean(terminal_error**2) + np.sum(np.mean(compensated_jumps,0)**2)) 478 | print('||err_Y||^2: ', np.mean(MSE_t)) 479 | 480 | 481 | 482 | 483 | 484 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------