├── functions ├── C │ ├── BS_sor │ ├── PDE_solver.h │ ├── BS_SOR_main.c │ ├── SOR.h │ ├── Makefile │ ├── mainSOR.c │ ├── PDE_solver.c │ └── SOR.c ├── cython │ ├── cython_Heston.cpython-36m-x86_64-linux-gnu.so │ ├── cython_Heston.cpython-37m-x86_64-linux-gnu.so │ ├── cython_functions.cpython-36m-x86_64-linux-gnu.so │ ├── cython_functions.cpython-37m-x86_64-linux-gnu.so │ ├── setup.py │ ├── cython_functions.pyx │ └── cython_Heston.pyx ├── Parameters.py ├── probabilities.py ├── cost_utils.py ├── CF.py ├── Solvers.py ├── TC_pricer.py ├── Processes.py ├── Merton_pricer.py ├── NIG_pricer.py ├── BS_pricer.py └── VG_pricer.py ├── A.3 Introduction to Lévy processes and PIDEs.pdf ├── .gitignore ├── docker_start_notebook.py ├── latex └── A.3 Introduction to Lévy processes and PIDEs.bbl ├── README.md ├── A.2 Optimize and speed up the code. (SOR algorithm, Cython and C).ipynb ├── LICENSE └── 2.3 American Options.ipynb /functions/C/BS_sor: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/functions/C/BS_sor -------------------------------------------------------------------------------- /A.3 Introduction to Lévy processes and PIDEs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/A.3 Introduction to Lévy processes and PIDEs.pdf -------------------------------------------------------------------------------- /functions/cython/cython_Heston.cpython-36m-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/functions/cython/cython_Heston.cpython-36m-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /functions/cython/cython_Heston.cpython-37m-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/functions/cython/cython_Heston.cpython-37m-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /functions/cython/cython_functions.cpython-36m-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/functions/cython/cython_functions.cpython-36m-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /functions/cython/cython_functions.cpython-37m-x86_64-linux-gnu.so: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lazyprogrammer/Financial-Models-Numerical-Methods/HEAD/functions/cython/cython_functions.cpython-37m-x86_64-linux-gnu.so -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.aux 2 | #*.bbl 3 | *.blg 4 | *.log 5 | *.maf 6 | *.toc 7 | *.mtc* 8 | *.out 9 | *backup 10 | 11 | *.sty 12 | *.png 13 | #*.pdf 14 | *~ 15 | 16 | .ipynb_checkpoints 17 | temp/ 18 | functions/__pycache__/ 19 | functions/cython/build/ 20 | functions/cython/__pycache__/ 21 | functions/C/*.o 22 | -------------------------------------------------------------------------------- /functions/C/PDE_solver.h: -------------------------------------------------------------------------------- 1 | #ifndef PDE_SOLVER_H 2 | #define PDE_SOLVER_H 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | #include "SOR.h" 9 | #include 10 | 11 | double PDE_SOR(int Ns, int Nt, double S, double K, double T, double sig, double r, double w); 12 | 13 | 14 | #endif 15 | -------------------------------------------------------------------------------- /functions/C/BS_SOR_main.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "SOR.h" 5 | #include "PDE_solver.h" 6 | #include 7 | 8 | 9 | 10 | 11 | int main() 12 | { 13 | 14 | double r = 0.1; 15 | double sig = 0.2; 16 | double S = 100.0; 17 | double K = 100.0; 18 | double T = 1.; 19 | 20 | int Nspace = 3000; // space steps 21 | int Ntime = 2000; // time steps 22 | 23 | double w = 1.68; // relaxation parameter 24 | 25 | printf("The price is: %f \n ", PDE_SOR(Nspace,Ntime,S,K,T,sig,r,w) ); 26 | 27 | return 0; 28 | } 29 | 30 | 31 | -------------------------------------------------------------------------------- /functions/cython/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Tue Oct 15 17:49:22 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | # Compile with: 10 | # python setup.py build_ext --inplace 11 | 12 | 13 | 14 | from distutils.core import setup 15 | from Cython.Build import cythonize 16 | import numpy 17 | 18 | 19 | 20 | setup( 21 | ext_modules = cythonize("cython_functions.pyx", language_level='3'), 22 | include_dirs = [numpy.get_include()] 23 | ) 24 | 25 | 26 | setup( 27 | ext_modules = cythonize("cython_Heston.pyx", language_level='3'), 28 | include_dirs = [numpy.get_include()] 29 | ) 30 | -------------------------------------------------------------------------------- /functions/C/SOR.h: -------------------------------------------------------------------------------- 1 | #ifndef SOR_H 2 | #define SOR_H 3 | 4 | 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | static const int N = 4; 11 | 12 | void print_matrix(double arr[N][N]); 13 | void print_array(double* arr); 14 | 15 | double* SOR(double A[N][N], double* b, double w, double eps, int N_max); 16 | double* SOR_trid(double A[N][N], double* b, double w, double eps, int N_max); 17 | double* SOR_abc(double aa, double bb, double cc, double* b, int NN, double w, double eps, int N_max); 18 | double* SOR_aabbcc(double aa, double bb, double cc, double *b, double *x0, double *x1, 19 | int NN, double w, double eps, int N_max); 20 | 21 | 22 | double dist_square(double* a, double* b); 23 | double dist_square2(double* a, double* b, int NN); 24 | void print_array_2(double* arr, int NN); 25 | 26 | #endif 27 | -------------------------------------------------------------------------------- /functions/C/Makefile: -------------------------------------------------------------------------------- 1 | PROGRAM_NAME=BS_sor 2 | OBJECTS=BS_SOR_main.o SOR.o PDE_solver.o 3 | 4 | CXX=gcc #clang 5 | 6 | 7 | CXXFLAGS +=-Wall -Werror 8 | LIBS=-lm 9 | 10 | 11 | 12 | 13 | $(PROGRAM_NAME):$(OBJECTS) 14 | $(CXX) $(CXXFLAGS) -o $(PROGRAM_NAME) $(OBJECTS) $(LIBS) 15 | 16 | @echo " " 17 | @echo "Compilation completed!" 18 | @echo " " 19 | 20 | 21 | 22 | BS_SOR_main.o:SOR.h PDE_solver.h BS_SOR_main.c 23 | $(CXX) $(CXXFLAGS) -c -o BS_SOR_main.o BS_SOR_main.c 24 | 25 | 26 | SOR.o:SOR.h SOR.c 27 | $(CXX) $(CXXFLAGS) -c -o SOR.o SOR.c 28 | 29 | 30 | PDE_solver.o:SOR.h SOR.c PDE_solver.h PDE_solver.c 31 | $(CXX) $(CXXFLAGS) -c -o PDE_solver.o PDE_solver.c 32 | 33 | 34 | 35 | clean: 36 | rm -f *.o 37 | rm -f *~ 38 | rm -f core 39 | 40 | 41 | cat: 42 | cat Makefile 43 | 44 | 45 | all: $(PROGRAM_NAME) clean 46 | -------------------------------------------------------------------------------- /functions/Parameters.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Jun 10 09:56:25 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | class Option_param(): 10 | """ 11 | Option class wants the option parameters: 12 | S0 = current stock price 13 | K = Strike price 14 | T = time to maturity 15 | exercise = European or American 16 | """ 17 | def __init__(self, S0=15, K=15, T=1, payoff="call", exercise="European"): 18 | self.S0 = S0 19 | self.K = K 20 | self.T = T 21 | 22 | if (exercise=="European" or exercise=="American"): 23 | self.exercise = exercise 24 | else: 25 | raise ValueError("invalid type. Set 'European' or 'American'") 26 | 27 | if (payoff=="call" or payoff=="put"): 28 | self.payoff = payoff 29 | else: 30 | raise ValueError("invalid type. Set 'call' or 'put'") 31 | 32 | 33 | -------------------------------------------------------------------------------- /docker_start_notebook.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Jul 12 19:01:20 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import os 10 | from webbrowser import open_new_tab 11 | from time import sleep 12 | import threading 13 | 14 | port_doc = "8888" 15 | port_web = "8888" 16 | name = "Numeric_Finance" 17 | 18 | UID = os.getuid() 19 | PWD = os.getcwd() 20 | image = "jupyter/scipy-notebook:82d1d0bf0867" 21 | # Alternatives: 22 | #jupyter/scipy-notebook #"jupyter/tensorflow-notebook" #jupyter/all-spark-notebook 23 | script = "start-notebook.sh" 24 | 25 | 26 | cmd_line = ("docker run --rm -d -p {}:{} \ 27 | --name {} \ 28 | --user {} \ 29 | --group-add users \ 30 | -v {}:/home/jovyan/work \ 31 | {} {} --NotebookApp.token='' ".format(port_doc, port_web, name, UID, PWD, image, script) ) 32 | 33 | 34 | thread = threading.Thread( target= os.system(cmd_line) ) 35 | thread.start() 36 | thread.join() 37 | 38 | print(cmd_line) 39 | sleep(0.8) # docker is slow to open 40 | open_new_tab("http://localhost:{}/tree/work".format(port_web)) 41 | 42 | 43 | -------------------------------------------------------------------------------- /functions/C/mainSOR.c: -------------------------------------------------------------------------------- 1 | #include "SOR.h" 2 | 3 | 4 | 5 | /* 6 | GENERAL MATRIX (DIAGONAL DOMINANT) 7 | 8 | double A[4][4] = { {10, 5, 2, 1}, 9 | {2, 15, 2, 3}, 10 | {1, 8, 13, 1}, 11 | {2, 3, 1, 8} }; 12 | double b[4] = {30, 50, 60, 43}; 13 | double* x = SOR(A,b, w,eps, N_max); 14 | 15 | TRIDIAGONAL MATRIX 16 | double A[4][4] = { {10, 5, 0, 0}, 17 | {2, 15, 2, 0}, 18 | {0, 8, 13, 1}, 19 | {0, 0, 1, 8} }; 20 | double b[4] = {20, 38, 59, 35}; 21 | double* x = SOR_trid(A, b, w, eps, N_max); 22 | */ 23 | 24 | 25 | 26 | int main() 27 | { 28 | // TRIDIAGONAL WITH CONSTANT aa,bb,cc 29 | double A[4][4] = { {10, 5, 0, 0}, 30 | {2, 10, 5, 0}, 31 | {0, 2, 10, 5}, 32 | {0, 0, 2, 10} }; 33 | 34 | double b[4] = {20, 37, 54, 46}; 35 | 36 | double aa=2, bb=10, cc=5; 37 | 38 | 39 | const double w = 1; 40 | const double eps = 1e-10; 41 | const int N_max = 100; 42 | 43 | 44 | printf("Matrix A: \n"); 45 | print_matrix(A); 46 | printf("Vector b: \n"); 47 | print_array(b); 48 | 49 | // double* x = SOR_abc(aa, bb, cc, b, N, w, eps, N_max); 50 | 51 | double* x0 = calloc(N, sizeof(double) ); 52 | double* x1 = calloc(N, sizeof(double) ); 53 | double* x = SOR_aabbcc(aa, bb, cc, b, x0, x1, N, w, eps, N_max); 54 | 55 | printf("Solution x: \n"); 56 | print_array(x); 57 | 58 | free(x0); 59 | free(x1); 60 | 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /functions/cython/cython_functions.pyx: -------------------------------------------------------------------------------- 1 | """ 2 | Created on Mon Jul 29 11:13:45 2019 3 | 4 | @author: cantaro86 5 | """ 6 | 7 | import numpy as np 8 | from scipy.linalg import norm 9 | cimport numpy as np 10 | cimport cython 11 | 12 | cdef np.float64_t distance2(np.float64_t[:] a, np.float64_t[:] b, unsigned int N): 13 | cdef np.float64_t dist = 0 14 | cdef unsigned int i 15 | for i in range(N): 16 | dist += (a[i] - b[i]) * (a[i] - b[i]) 17 | return dist 18 | 19 | 20 | @cython.boundscheck(False) 21 | @cython.wraparound(False) 22 | def SOR(np.float64_t aa, 23 | np.float64_t bb, np.float64_t cc, 24 | np.float64_t[:] b, 25 | np.float64_t w=1, np.float64_t eps=1e-10, unsigned int N_max = 500): 26 | 27 | cdef unsigned int N = b.size 28 | 29 | cdef np.float64_t[:] x0 = np.ones(N, dtype=np.float64) # initial guess 30 | cdef np.float64_t[:] x_new = np.ones(N, dtype=np.float64) # new solution 31 | 32 | 33 | cdef unsigned int i, k 34 | cdef np.float64_t S 35 | 36 | for k in range(1,N_max+1): 37 | for i in range(N): 38 | if (i==0): 39 | S = cc * x_new[1] 40 | elif (i==N-1): 41 | S = aa * x_new[N-2] 42 | else: 43 | S = aa * x_new[i-1] + cc * x_new[i+1] 44 | x_new[i] = (1-w)*x_new[i] + (w/bb) * (b[i] - S) 45 | if distance2(x_new, x0, N) < eps*eps: 46 | return x_new 47 | x0[:] = x_new 48 | if k==N_max: 49 | print("Fail to converge in {} iterations".format(k)) 50 | return x_new 51 | -------------------------------------------------------------------------------- /functions/probabilities.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Oct 7 18:33:39 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import numpy as np 10 | from scipy.integrate import quad 11 | from functools import partial 12 | from functions.CF import cf_Heston_good 13 | 14 | 15 | def Q1(k, cf, right_lim): 16 | """ 17 | P(X= 0 and (1+cost_b) * np.exp(x[i]) <= K : 37 | cost[i][j] = (1-cost_s) * y[j] * np.exp(x[i]) 38 | 39 | elif y[j]-1 >= 0 and (1+cost_b) * np.exp(x[i]) > K : 40 | cost[i][j] = ( (1-cost_s) * (y[j]-1) * np.exp(x[i]) ) + K 41 | 42 | elif y[j]-1 < 0 and (1+cost_b) * np.exp(x[i]) > K : 43 | cost[i][j] = ( (1+cost_b) * (y[j]-1) * np.exp(x[i]) ) + K 44 | 45 | return cost 46 | 47 | 48 | def buyer(x,y,cost_b,cost_s,K): 49 | 50 | cost = np.zeros( (len(x),len(y)) ) 51 | 52 | for i in range(len(x)): 53 | for j in range(len(y)): 54 | 55 | if y[j] < 0 and (1+cost_b) * np.exp(x[i]) <= K : 56 | cost[i][j] = (1+cost_b) * y[j] * np.exp(x[i]) 57 | 58 | elif y[j] >= 0 and (1+cost_b) * np.exp(x[i]) <= K : 59 | cost[i][j] = (1-cost_s) * y[j] * np.exp(x[i]) 60 | 61 | elif y[j]+1 >= 0 and (1+cost_b) * np.exp(x[i]) > K : 62 | cost[i][j] = ( (1-cost_s) * (y[j]+1) * np.exp(x[i]) ) - K 63 | 64 | elif y[j]+1 < 0 and (1+cost_b) * np.exp(x[i]) > K : 65 | cost[i][j] = ( (1+cost_b) * (y[j]+1) * np.exp(x[i]) ) - K 66 | 67 | return cost 68 | -------------------------------------------------------------------------------- /functions/C/PDE_solver.c: -------------------------------------------------------------------------------- 1 | #include "PDE_solver.h" 2 | 3 | 4 | 5 | 6 | double PDE_SOR(int Ns, int Nt, double S, double K, double T, double sig, double r, double w) 7 | { 8 | 9 | const double eps = 1e-10; 10 | const int N_max = 600; 11 | 12 | double S_max = 3*K; 13 | double S_min = K/3; 14 | double x_max = log(S_max); 15 | double x_min = log(S_min); 16 | 17 | double dx = (x_max - x_min)/(Ns-1); 18 | double dt = T/Nt; 19 | 20 | double sig2 = sig*sig; 21 | double dxx = dx * dx; 22 | double aa = ( (dt/2) * ( (r-0.5*sig2)/dx - sig2/dxx ) ); 23 | double bb = ( 1 + dt * ( sig2/dxx + r ) ); 24 | double cc = (-(dt/2) * ( (r-0.5*sig2)/dx + sig2/dxx ) ); 25 | 26 | 27 | // array allocations 28 | double *x = calloc(Ns, sizeof(double) ); 29 | double *x_old = calloc(Ns-2, sizeof(double) ); 30 | double *x_new = calloc(Ns-2, sizeof(double) ); 31 | double *help_ptr = calloc(Ns-2, sizeof(double) ); 32 | double *temp; 33 | 34 | for (unsigned int i=0; i=0; --k) 43 | { 44 | x_old[Ns-3] -= cc * ( S_max - K * exp( -r*(T-k*dt) ) ); // offset 45 | x_new = SOR_aabbcc(aa, bb, cc, x_old, help_ptr, x_new, Ns-2, w, eps, N_max); //SOR solver 46 | // x_new = SOR_abc(aa, bb, cc, x_old, Ns-2, w, eps, N_max); //SOR solver 47 | 48 | if (k != 0) // swap the pointers (we don't need to allocate new memory) 49 | { 50 | temp = x_old; 51 | x_old = x_new; 52 | x_new = temp; 53 | } 54 | } 55 | free(help_ptr); 56 | free(x_old); 57 | 58 | // x_new is the solution!! 59 | 60 | // binary search: Search for the points for the interpolation 61 | 62 | int low = 1; 63 | int high = Ns-2; 64 | int mid; 65 | double result = -1; 66 | 67 | if (S > x[high] || S < x[low]) 68 | { 69 | printf("error: Price S out of grid.\n"); 70 | free(x_new); 71 | free(x); 72 | return result; 73 | } 74 | 75 | while ( (low+1) != high) 76 | { 77 | 78 | mid = (low + high) / 2; 79 | 80 | if ( fabs(x[mid]-S)< 1e-10 ) 81 | { 82 | result = x_new[mid-1]; 83 | free(x_new); 84 | free(x); 85 | return result; 86 | } 87 | else if ( x[mid] < S) 88 | { 89 | low = mid; 90 | } 91 | else 92 | { 93 | high = mid; 94 | } 95 | } 96 | 97 | // linear interpolation 98 | result = x_new[low-1] + (S - x[low]) * (x_new[high-1] - x_new[low-1]) / (x[high] - x[low]) ; 99 | free(x_new); 100 | free(x); 101 | return result; 102 | } 103 | -------------------------------------------------------------------------------- /functions/CF.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Oct 7 17:57:19 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import numpy as np 10 | 11 | 12 | def cf_normal(u, mu=1, sig=2): 13 | """ 14 | Characteristic function of a Normal random variable 15 | """ 16 | return np.exp( 1j * u * mu - 0.5 * u**2 * sig**2 ) 17 | 18 | def cf_gamma(u, a=1, b=2): 19 | """ 20 | Characteristic function of a Gamma random variable 21 | - shape: a 22 | - scale: b 23 | """ 24 | return (1 - b * u * 1j)**(-a) 25 | 26 | def cf_poisson(u, lam=1): 27 | """ 28 | Characteristic function of a Poisson random variable 29 | - rate: lam 30 | """ 31 | return np.exp( lam * (np.exp(1j * u) -1) ) 32 | 33 | 34 | def cf_mert(u, t=1, mu=1, sig=2, lam=0.8, muJ=0, sigJ=0.5): 35 | """ 36 | Characteristic function of a Merton random variable at time t 37 | mu: drift 38 | sig: diffusion coefficient 39 | lam: jump activity 40 | muJ: jump mean size 41 | sigJ: jump size standard deviation 42 | """ 43 | return np.exp( t * ( 1j * u * mu - 0.5 * u**2 * sig**2 \ 44 | + lam*( np.exp(1j*u*muJ - 0.5 * u**2 * sigJ**2) -1 ) ) ) 45 | 46 | 47 | def cf_VG(u, t=1, mu=0, theta=-0.1, sigma=0.2, kappa=0.1): 48 | """ 49 | Characteristic function of a Variance Gamma random variable at time t 50 | mu: additional drift 51 | theta: Brownian motion drift 52 | sigma: Brownian motion diffusion 53 | kappa: Gamma process variance 54 | """ 55 | return np.exp( t * ( 1j*mu*u - np.log(1 - 1j*theta*kappa*u + 0.5*kappa*sigma**2 * u**2 ) /kappa ) ) 56 | 57 | 58 | def cf_NIG(u, t=1, mu=0, theta=-0.1, sigma=0.2, kappa=0.1): 59 | """ 60 | Characteristic function of a Normal Inverse Gaussian random variable at time t 61 | mu: additional drift 62 | theta: Brownian motion drift 63 | sigma: Brownian motion diffusion 64 | kappa: Inverse Gaussian process variance 65 | """ 66 | return np.exp( t * ( 1j*mu*u + 1/kappa - np.sqrt(1 - 2j*theta*kappa*u + kappa*sigma**2 * u**2 ) /kappa ) ) 67 | 68 | 69 | def cf_Heston(u, t, v0, mu, kappa, theta, sigma, rho): 70 | """ 71 | Heston characteristic function as proposed in the original paper of Heston (1993) 72 | """ 73 | xi = kappa - sigma*rho*u*1j 74 | d = np.sqrt( xi**2 + sigma**2 * (u**2 + 1j*u) ) 75 | g1 = (xi+d)/(xi-d) 76 | cf = np.exp( 1j*u*mu*t + (kappa*theta)/(sigma**2) * ( (xi+d)*t - 2*np.log( (1-g1*np.exp(d*t))/(1-g1) ))\ 77 | + (v0/sigma**2)*(xi+d) * (1-np.exp(d*t))/(1-g1*np.exp(d*t)) ) 78 | return cf 79 | 80 | 81 | def cf_Heston_good(u, t, v0, mu, kappa, theta, sigma, rho): 82 | """ 83 | Heston characteristic function as proposed by Schoutens (2004) 84 | """ 85 | xi = kappa - sigma*rho*u*1j 86 | d = np.sqrt( xi**2 + sigma**2 * (u**2 + 1j*u) ) 87 | g1 = (xi+d)/(xi-d) 88 | g2 = 1/g1 89 | cf = np.exp( 1j*u*mu*t + (kappa*theta)/(sigma**2) * ( (xi-d)*t - 2*np.log( (1-g2*np.exp(-d*t))/(1-g2) ))\ 90 | + (v0/sigma**2)*(xi-d) * (1-np.exp(-d*t))/(1-g2*np.exp(-d*t)) ) 91 | return cf 92 | -------------------------------------------------------------------------------- /functions/Solvers.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Jul 27 11:13:45 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import numpy as np 10 | from scipy import sparse 11 | from scipy.linalg import norm, solve_triangular 12 | from scipy.linalg.lapack import get_lapack_funcs 13 | from scipy.linalg.misc import LinAlgError 14 | 15 | 16 | def Thomas(A, b): 17 | """ 18 | Solver for the linear equation Ax=b using the Thomas algorithm. 19 | It is a wrapper of the LAPACK function dgtsv. 20 | """ 21 | 22 | D = A.diagonal(0) 23 | L = A.diagonal(-1) 24 | U = A.diagonal(1) 25 | 26 | if len(A.shape) != 2 or A.shape[0] != A.shape[1]: 27 | raise ValueError('expected square matrix') 28 | if A.shape[0] != b.shape[0]: 29 | raise ValueError('incompatible dimensions') 30 | 31 | dgtsv, = get_lapack_funcs(('gtsv',)) 32 | du2,d,du,x,info = dgtsv(L, D, U, b) 33 | 34 | if info == 0: 35 | return x 36 | if info > 0: 37 | raise LinAlgError("singular matrix: resolution failed at diagonal %d" % 38 | (info-1)) 39 | 40 | 41 | def SOR(A, b, w=1, eps=1e-10, N_max = 100): 42 | """ 43 | Solver for the linear equation Ax=b using the SOR algorithm. 44 | A = L + D + U 45 | Arguments: 46 | L = Strict Lower triangular matrix 47 | D = Diagonal 48 | U = Strict Upper triangular matrix 49 | w = Relaxation coefficient 50 | eps = tollerance 51 | N_max = Max number of iterations 52 | """ 53 | 54 | x0 = b.copy() # initial guess 55 | 56 | if sparse.issparse(A): 57 | D = sparse.diags(A.diagonal()) # diagonal 58 | U = sparse.triu(A, k=1) # Strict U 59 | L = sparse.tril(A, k=-1) # Strict L 60 | DD = (w*L + D).toarray() 61 | else: 62 | D = np.eye(A.shape[0]) * np.diag(A) # diagonal 63 | U = np.triu(A, k=1) # Strict U 64 | L = np.tril(A, k=-1) # Strict L 65 | DD = (w*L + D) 66 | 67 | for i in range(1,N_max+1): 68 | x_new = solve_triangular( DD, (w*b - w*U@x0 - (w-1)*D@x0), lower=True) 69 | if norm(x_new - x0) < eps: 70 | return x_new 71 | x0 = x_new 72 | if i==N_max: 73 | raise ValueError("Fail to converge in {} iterations".format(i)) 74 | 75 | 76 | def SOR2(A, b, w=1, eps=1e-10, N_max = 100): 77 | """ 78 | Solver for the linear equation Ax=b using the SOR algorithm. 79 | It uses the coefficients and not the matrix multiplication. 80 | """ 81 | N = len(b) 82 | x0 = np.ones_like(b, dtype=np.float64) # initial guess 83 | x_new = np.ones_like(x0) # new solution 84 | 85 | for k in range(1,N_max+1): 86 | for i in range(N): 87 | S = 0 88 | for j in range(N): 89 | if j != i: 90 | S += A[i,j]*x_new[j] 91 | x_new[i] = (1-w)*x_new[i] + (w/A[i,i]) * (b[i] - S) 92 | 93 | if norm(x_new - x0) < eps: 94 | return x_new 95 | x0 = x_new.copy() 96 | if k==N_max: 97 | print("Fail to converge in {} iterations".format(k)) 98 | 99 | -------------------------------------------------------------------------------- /latex/A.3 Introduction to Lévy processes and PIDEs.bbl: -------------------------------------------------------------------------------- 1 | \begin{thebibliography}{} 2 | 3 | \bibitem[Applebaum, 2009]{Applebaum} 4 | Applebaum, D. (2009). 5 | \newblock {\em Lévy Processes and Stochastic Calculus}. 6 | \newblock Cambridge University Press; 2nd edition. 7 | 8 | \bibitem[Barndorff-Nielsen, 1997]{BN97} 9 | Barndorff-Nielsen (1997). 10 | \newblock Processes of {N}ormal inverse {G}aussian type. 11 | \newblock {\em Finance and Stochastics}, 2:41--68. 12 | 13 | \bibitem[Black and Scholes, 1973]{BS73} 14 | Black, F. and Scholes, M. (1973). 15 | \newblock The pricing of options and corporate liabilities. 16 | \newblock {\em The Journal of Political Economy}, 81(3):637--654. 17 | 18 | \bibitem[Carr et~al., 2002]{CGMY02} 19 | Carr, P., Geman, H., D.B., M., and M., Y. (2002). 20 | \newblock The fine structure of asset returns: An empirical investigation. 21 | \newblock {\em Journal of Business}, 75(2):305--333. 22 | 23 | \bibitem[Cont et~al., 1997]{BoPoCo97} 24 | Cont, R., Potters, M., and Bouchaud, J. (1997). 25 | \newblock Scaling in stock market data: stable laws and beyond. 26 | \newblock {\em Scale invariance and beyond, Springer}. 27 | 28 | \bibitem[Cont and Tankov, 2003]{Cont} 29 | Cont, R. and Tankov, P. (2003). 30 | \newblock {\em Financial Modelling with Jump Processes}. 31 | \newblock Chapman and Hall/CRC; 1 edition. 32 | 33 | \bibitem[Cont and Voltchkova, 2005a]{CoVo05b} 34 | Cont, R. and Voltchkova, E. (2005a). 35 | \newblock A finite difference scheme for option pricing in jump diffusion and 36 | exponential {L}\'evy models. 37 | \newblock {\em SIAM Journal of numerical analysis}, 43(4):1596--1626. 38 | 39 | \bibitem[Cont and Voltchkova, 2005b]{CoVo05} 40 | Cont, R. and Voltchkova, E. (2005b). 41 | \newblock Integro-differential equations for option prices in exponential 42 | {L}èvy models. 43 | \newblock {\em Finance and Stochastics}, 9:299--325. 44 | 45 | \bibitem[Eberlein and Keller, 1995]{EbKe95} 46 | Eberlein, E. and Keller, U. (1995). 47 | \newblock Hyperbolic distributions in finance. 48 | \newblock {\em Bernoulli}, 1(3):281--299. 49 | 50 | \bibitem[Kabasinskas et~al., 2009]{alpha09} 51 | Kabasinskas, A., Rachev, S., Sakalauskas, L., Wei, S., and Belovas, I. (2009). 52 | \newblock Alpha-stable paradigm in financial markets. 53 | \newblock {\em Journal of Computational Analysis and Applications}, 54 | 11(4):641--669. 55 | 56 | \bibitem[Kou, 2002]{Kou02} 57 | Kou, S. (2002). 58 | \newblock A jump-diffusion model for option pricing. 59 | \newblock {\em Management Science}, 48(8):1086--1101. 60 | 61 | \bibitem[Madan et~al., 1998]{MCC98} 62 | Madan, D., Carr, P., and Chang, E. (1998). 63 | \newblock The {V}ariance {G}amma process and option pricing. 64 | \newblock {\em European Finance Review}, 2:79–105. 65 | 66 | \bibitem[Madan and Seneta, 1990]{MaSe90} 67 | Madan, D. and Seneta, E. (1990). 68 | \newblock The {V}ariance {G}amma {(V.G.)} model for share market returns. 69 | \newblock {\em The journal of Business}, 63(4):511--524. 70 | 71 | \bibitem[Mandelbrot, 1963]{Ma63} 72 | Mandelbrot, B. (1963). 73 | \newblock Modeling financial data with stable distributions. 74 | \newblock {\em Journal of Business}, XXXVI(1):392--417. 75 | 76 | \bibitem[Merton, 1976]{Me76} 77 | Merton, R. (1976). 78 | \newblock Option pricing when underlying stock returns are discontinuous. 79 | \newblock {\em Journal of Financial Economics}, 3:125--144. 80 | 81 | \bibitem[Papapantoleon, ]{papapa} 82 | Papapantoleon, A. 83 | \newblock An introduction to lévy processes with applications in finance. 84 | \newblock {\em Available in Arxiv}. 85 | 86 | \bibitem[Sato, 1999]{Sato} 87 | Sato, K.~I. (1999). 88 | \newblock {\em Lévy processes and infinitely divisible distributions}. 89 | \newblock Cambridge University Press. 90 | 91 | \bibitem[Schoutens, 2003]{Schoutens} 92 | Schoutens, W. (2003). 93 | \newblock {\em L\'evy processes in finance}. 94 | \newblock Wiley, First Edition. 95 | 96 | \end{thebibliography} 97 | -------------------------------------------------------------------------------- /functions/C/SOR.c: -------------------------------------------------------------------------------- 1 | #include "SOR.h" 2 | 3 | 4 | 5 | double dist_square(double* a, double* b) 6 | { 7 | double dist = 0; 8 | 9 | for (int i=0; i sigma**2) # Feller condition 51 | 52 | cdef double[:] W_S # declaration Brownian motion for S 53 | cdef double[:] W_v # declaration Brownian motion for v 54 | 55 | # Initialize 56 | cdef double[:] v_T = np.zeros(paths) # values of v at T 57 | cdef double[:] S_T = np.zeros(paths) # values of S at T 58 | cdef double[:] v = np.zeros(N) 59 | cdef double[:] S = np.zeros(N) 60 | 61 | cdef int t, path 62 | for path in range(paths): 63 | # Generate random Brownian Motions 64 | W_S_arr = np.random.normal(loc=0, scale=1, size=N-1 ) 65 | W_v_arr = rho * W_S_arr + sqrt(1-rho**2) * np.random.normal(loc=0, scale=1, size=N-1 ) 66 | W_S = W_S_arr 67 | W_v = W_v_arr 68 | S[0] = S0 # stock at 0 69 | v[0] = v0 # variance at 0 70 | 71 | for t in range(0,N-1): 72 | v[t+1] = fabs( v[t] + kappa*(theta - v[t])*dt + sigma * sqrt(v[t]) * dt_sq * W_v[t] ) 73 | S[t+1] = S[t] * exp( (mu - 0.5*v[t])*dt + sqrt(v[t]) * dt_sq * W_S[t] ) 74 | 75 | S_T[path] = S[N-1] 76 | v_T[path] = v[N-1] 77 | 78 | return np.asarray(S_T), np.asarray(v_T) 79 | 80 | 81 | 82 | 83 | cpdef Heston_paths_log(int N, int paths, double T, double S0, double v0, 84 | double mu, double rho, double kappa, double theta, double sigma ): 85 | """ 86 | Generates random values of stock S and variance v at maturity T. 87 | This function uses the log-variables. NaN and abnormal numbers are ignored. 88 | 89 | OUTPUT: 90 | Two arrays of size smaller or equal of "paths". 91 | 92 | INPUT: 93 | int N = time steps 94 | int paths = number of paths 95 | double T = maturity 96 | double S0 = spot price 97 | double v0 = spot variance 98 | double mu = drift 99 | double rho = correlation coefficient 100 | double kappa = mean reversion coefficient 101 | double theta = long-term variance 102 | double sigma = Vol of Vol - Volatility of instantaneous variance 103 | """ 104 | 105 | cdef double dt = T/(N-1) 106 | cdef double dt_sq = sqrt(dt) 107 | 108 | cdef double X0 = log(S0) # log price 109 | cdef double Y0 = log(v0) # log-variance 110 | 111 | assert(2*kappa * theta > sigma**2) # Feller condition 112 | cdef double std_asy = sqrt( theta * sigma**2 /(2*kappa) ) 113 | 114 | cdef double[:] W_S # declaration Brownian motion for S 115 | cdef double[:] W_v # declaration Brownian motion for v 116 | 117 | # Initialize 118 | cdef double[:] Y_T = np.zeros(paths) 119 | cdef double[:] X_T = np.zeros(paths) 120 | cdef double[:] Y = np.zeros(N) 121 | cdef double[:] X = np.zeros(N) 122 | 123 | cdef int t, path 124 | cdef double v, v_sq 125 | cdef double up_bound = log( (theta + 10*std_asy) ) # mean + 10 standard deviations 126 | cdef int warning = 0 127 | cdef int counter = 0 128 | 129 | # Generate paths 130 | for path in range(paths): 131 | # Generate random Brownian Motions 132 | W_S_arr = np.random.normal(loc=0, scale=1, size=N-1 ) 133 | W_v_arr = rho * W_S_arr + sqrt(1-rho**2) * np.random.normal(loc=0, scale=1, size=N-1 ) 134 | W_S = W_S_arr 135 | W_v = W_v_arr 136 | X[0] = X0 # log-stock 137 | Y[0] = Y0 # log-variance 138 | 139 | for t in range(0,N-1): 140 | v = exp(Y[t]) # variance 141 | v_sq = sqrt(v) # square root of variance 142 | 143 | Y[t+1] = Y[t] + (1/v)*( kappa*(theta - v) - 0.5*sigma**2 )*dt + sigma * (1/v_sq) * dt_sq * W_v[t] 144 | X[t+1] = X[t] + (mu - 0.5*v)*dt + v_sq * dt_sq * W_S[t] 145 | 146 | if ( Y[-1] > up_bound or isnan(Y[-1]) ): 147 | warning = 1 148 | counter += 1 149 | X_T[path] = 10000 150 | Y_T[path] = 10000 151 | continue 152 | 153 | X_T[path] = X[-1] 154 | Y_T[path] = Y[-1] 155 | 156 | if (warning==1): 157 | print("WARNING. ", counter, " paths have been removed because of the overflow.") 158 | print("SOLUTION: Use a bigger value N.") 159 | 160 | Y_arr = np.asarray(Y_T) 161 | Y_good = Y_arr[ Y_arr < up_bound ] 162 | X_good = np.asarray(X_T)[ Y_arr < up_bound ] 163 | 164 | return np.exp(X_good), np.exp(Y_good) 165 | -------------------------------------------------------------------------------- /functions/Processes.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sat Jul 27 17:06:01 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import numpy as np 10 | import scipy.stats as ss 11 | 12 | 13 | class Diffusion_process(): 14 | """ 15 | Class for the diffusion process: 16 | r = risk free constant rate 17 | sig = constant diffusion coefficient 18 | mu = constant drift 19 | """ 20 | def __init__(self, r=0.1, sig=0.2, mu=0.1): 21 | self.r = r 22 | self.mu = mu 23 | if (sig<=0): 24 | raise ValueError("sig must be positive") 25 | else: 26 | self.sig = sig 27 | 28 | def exp_RV(self, S0, T, N): 29 | W = ss.norm.rvs( (self.r-0.5*self.sig**2)*T , np.sqrt(T)*self.sig, N) 30 | S_T = S0 * np.exp(W) 31 | return S_T 32 | 33 | 34 | 35 | class Merton_process(): 36 | """ 37 | Class for the Merton process: 38 | r = risk free constant rate 39 | sig = constant diffusion coefficient 40 | lam = jump activity 41 | muJ = jump mean 42 | sigJ = jump standard deviation 43 | """ 44 | def __init__(self, r=0.1, sig=0.2, lam = 0.8, muJ = 0, sigJ = 0.5): 45 | self.r = r 46 | self.lam = lam 47 | self.muJ = muJ 48 | if (sig<0 or sigJ<0): 49 | raise ValueError("sig and sigJ must be positive") 50 | else: 51 | self.sig = sig 52 | self.sigJ = sigJ 53 | 54 | # moments 55 | self.var = self.sig**2 + self.lam * self.sigJ**2 + self.lam * self.muJ**2 56 | self.skew = self.lam * (3* self.sigJ**2 * self.muJ + self.muJ**3) / self.var**(1.5) 57 | self.kurt = self.lam * (3* self.sigJ**3 + 6 * self.sigJ**2 * self.muJ**2 + self.muJ**4) / self.var**2 58 | 59 | def exp_RV(self, S0, T, N): 60 | m = self.lam * (np.exp(self.muJ + (self.sigJ**2)/2) -1) # coefficient m 61 | W = ss.norm.rvs(0, 1, N) # The normal RV vector 62 | P = ss.poisson.rvs(self.lam*T, size=N) # Poisson random vector (number of jumps) 63 | Jumps = np.asarray([ss.norm.rvs(self.muJ, self.sigJ, ind).sum() for ind in P ]) # Jumps vector 64 | S_T = S0 * np.exp( (self.r - 0.5*self.sig**2 -m )*T + np.sqrt(T)*self.sig*W + Jumps ) # Martingale exponential Merton 65 | return S_T 66 | 67 | 68 | 69 | class VG_process(): 70 | """ 71 | Class for the Variance Gamma process: 72 | r = risk free constant rate 73 | Using the representation of Brownian subordination, the parameters are: 74 | theta = drift of the Brownian motion 75 | sigma = standard deviation of the Brownian motion 76 | kappa = variance of the of the Gamma process 77 | """ 78 | def __init__(self, r=0.1, sigma=0.2, theta=-0.1, kappa=0.1): 79 | self.r = r 80 | self.theta = theta 81 | self.kappa = kappa 82 | if (sigma<0): 83 | raise ValueError("sigma must be positive") 84 | else: 85 | self.sigma = sigma 86 | 87 | # moments 88 | self.var = self.sigma**2 + self.theta**2 * self.kappa 89 | self.skew = (2 * self.theta**3 * self.kappa**2 + 3*self.sigma**2 * self.theta * self.kappa) / (self.var**(1.5)) 90 | self.kurt = ( 3*self.sigma**4 * self.kappa +12*self.sigma**2 * self.theta**2 \ 91 | * self.kappa**2 + 6*self.theta**4 * self.kappa**3 ) / (self.var**2) 92 | 93 | def exp_RV(self, S0, T, N): 94 | w = -np.log(1 - self.theta * self.kappa - self.kappa/2 * self.sigma**2 ) /self.kappa # coefficient w 95 | rho = 1 / self.kappa 96 | G = ss.gamma(rho * T).rvs(N) / rho # The gamma RV 97 | Norm = ss.norm.rvs(0,1,N) # The normal RV 98 | VG = self.theta * G + self.sigma * np.sqrt(G) * Norm # VG process at final time G 99 | S_T = S0 * np.exp( (self.r-w)*T + VG ) # Martingale exponential VG 100 | return S_T 101 | 102 | 103 | 104 | class Heston_process(): 105 | """ 106 | Class for the Heston process: 107 | r = risk free constant rate 108 | rho = correlation between stock noise and variance noise 109 | theta = long term mean of the variance process 110 | sigma = volatility coefficient of the variance process 111 | kappa = mean reversion coefficient for the variance process 112 | """ 113 | def __init__(self, mu=0.1, rho=0, sigma=0.2, theta=-0.1, kappa=0.1): 114 | self.mu = mu 115 | if (np.abs(rho)>1): 116 | raise ValueError("|rho| must be <=1") 117 | self.rho = rho 118 | if (theta<0 or sigma<0 or kappa<0): 119 | raise ValueError("sigma,theta,kappa must be positive") 120 | else: 121 | self.theta = theta 122 | self.sigma = sigma 123 | self.kappa = kappa 124 | 125 | def path(self, S0, v0, N, T=1): 126 | """ 127 | Produces one path of the Heston process. 128 | N = number of time steps 129 | T = Time in years 130 | Returns two arrays S (price) and v (variance). 131 | """ 132 | 133 | MU = np.array([0, 0]) 134 | COV = np.matrix([[1, self.rho], [self.rho, 1]]) 135 | W = ss.multivariate_normal.rvs( mean=MU, cov=COV, size=N-1 ) 136 | W_S = W[:,0] # Stock Brownian motion: W_1 137 | W_v = W[:,1] # Variance Brownian motion: W_2 138 | 139 | # Initialize vectors 140 | T_vec, dt = np.linspace(0,T,N, retstep=True ) 141 | dt_sq = np.sqrt(dt) 142 | 143 | X0 = np.log(S0) 144 | v = np.zeros(N) 145 | v[0] = v0 146 | X = np.zeros(N) 147 | X[0] = X0 148 | 149 | # Generate paths 150 | for t in range(0,N-1): 151 | v_sq = np.sqrt(v[t]) 152 | v[t+1] = np.abs( v[t] + self.kappa*(self.theta - v[t])*dt + self.sigma * v_sq * dt_sq * W_v[t] ) 153 | X[t+1] = X[t] + (self.mu - 0.5*v[t])*dt + v_sq * dt_sq * W_S[t] 154 | 155 | return np.exp(X), v 156 | 157 | 158 | 159 | class NIG_process(): 160 | """ 161 | Class for the Normal Inverse Gaussian process: 162 | r = risk free constant rate 163 | Using the representation of Brownian subordination, the parameters are: 164 | theta = drift of the Brownian motion 165 | sigma = standard deviation of the Brownian motion 166 | kappa = variance of the of the Gamma process 167 | """ 168 | def __init__(self, r=0.1, sigma=0.2, theta=-0.1, kappa=0.1): 169 | self.r = r 170 | self.theta = theta 171 | if (sigma<0 or kappa<0): 172 | raise ValueError("sigma and kappa must be positive") 173 | else: 174 | self.sigma = sigma 175 | self.kappa = kappa 176 | 177 | # moments 178 | self.var = self.sigma**2 + self.theta**2 * self.kappa 179 | self.skew = (3 * self.theta**3 * self.kappa**2 + 3*self.sigma**2 * self.theta * self.kappa) / (self.var**(1.5)) 180 | self.kurt = ( 3*self.sigma**4 * self.kappa +18*self.sigma**2 * self.theta**2 \ 181 | * self.kappa**2 + 15*self.theta**4 * self.kappa**3 ) / (self.var**2) 182 | 183 | def exp_RV(self, S0, T, N): 184 | lam = T**2 / self.kappa # scale for the IG process 185 | mu_s = T / lam # scaled mean 186 | w = ( 1 - np.sqrt( 1 - 2*self.theta*self.kappa -self.kappa*self.sigma**2) )/self.kappa 187 | IG = ss.invgauss.rvs(mu=mu_s, scale=lam, size=N) # The IG RV 188 | Norm = ss.norm.rvs(0,1,N) # The normal RV 189 | X = self.theta * IG + self.sigma * np.sqrt(IG) * Norm # NIG random vector 190 | S_T = S0 * np.exp( (self.r-w)*T + X ) # exponential dynamics 191 | return S_T 192 | 193 | 194 | 195 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Financial-Models-Numerical-Methods 2 | ================================== 3 | 4 | 5 | This is a collection of [Jupyter notebooks](https://jupyter.org/) based on different topics in the area of quantitative finance. 6 | 7 | 8 | ### Is this a tutorial? 9 | 10 | Almost! :) 11 | 12 | This is just a collection of topics and algorithms that in my opinion are interesting. 13 | 14 | It contains several topics that are not so popular nowadays, but that can be very powerful. 15 | Usually, topics such as PDE methods, Lévy processes, Fourier methods or Kalman filter are not very popular among practitioners, who prefers to work with more standard tools. 16 | The aim of these notebooks is to present these interesting topics, by showing their practical application through an interactive python implementation. 17 | 18 | 19 | ### Who are these notebooks for? 20 | 21 | Not for absolute beginners. 22 | 23 | These topics require a basic knowledge in stochastic calculus, financial mathematics and statistics. A basic knowledge of python programming is also necessary. 24 | 25 | In these notebooks I will not explain what is a call option, or what is a stochastic process, or a partial differential equation. 26 | However, every time I will introduce a concept, I will also add a link to the corresponding wiki page or to a reference manual. 27 | In this way, the reader will be able to immediately understand what I am talking about. 28 | 29 | These notes are for students in science, economics or finance who have followed at least one undergraduate course in financial mathematics and statistics. 30 | Self-taught students or practicioners should have read at least an introductiory books in financial mathematics. 31 | 32 | 33 | ### Why is it worth to read these notes? 34 | 35 | First of all, this is not a book! 36 | Every notebook is (almost) independent from the others. Therefore you can select only the notebook you are interested in! 37 | 38 | ```diff 39 | - Every notebook, contains python code ready to use! 40 | ``` 41 | 42 | It is not easy to find on internet examples of financial models implemented in python which are ready to use and well documented. 43 | I think that beginners in quantitative finance will find these notebooks very useful! 44 | 45 | Moreover, Jupyter notebooks are interactive i.e. you can run the code inside the notebook. 46 | This is probably the best way to study! 47 | 48 | If you open a notebook with Github or NBviewer, sometimes mathematical formulas are not displayed correctly. 49 | For this reason, I suggest you to clone/download the repository. 50 | 51 | 52 | ### Is this series of notebooks complete? 53 | 54 | **No!** 55 | I will upload more notebooks from time to time. 56 | 57 | At the moment, I'm interested in the areas of stochastic processes, Kalman Filter, statistics and much more. I will add more interesting notebooks on these topics in the future. 58 | 59 | If you have any kind of questions, or if you find some errors, or you have suggestions for improvements, feel free to contact me. 60 | This is my [linkedin](https://www.linkedin.com/in/nicolacantarutti) page. 61 | 62 | 63 | 64 | ### Contents 65 | 66 | 1.1) **Black-Scholes numerical methods** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.1%20Black-Scholes%20numerical%20methods.ipynb) *(lognormal distribution, change of measure, Monte Carlo, Binomial method)*. 67 | 68 | 1.2) **SDE simulation and statistics** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.2%20SDE%20simulations%20and%20statistics.ipynb) 69 | *(paths generation, Confidence intervals, Hypothesys testing, Geometric Brownian motion, Cox-Ingersoll-Ross process, Euler Maruyama method, parameters estimation)* 70 | 71 | 1.3) **Fourier inversion methods** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.3%20Fourier%20transform%20methods.ipynb) 72 | *(derivation of inversion formula, numerical inversion, option pricing)* 73 | 74 | 1.4) **SDE, Heston model** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.4%20SDE%20-%20Heston%20model.ipynb) 75 | *(correlated Brownian motions, Heston paths, Heston distribution, characteristic function, option pricing)* 76 | 77 | 1.5) **SDE, Lévy processes** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/1.5%20SDE%20-%20L%C3%A9vy%20processes.ipynb) 78 | *(Merton, Variance Gamma, NIG, path generation, parameter estimation)* 79 | 80 | 2.1) **The Black-Scholes PDE** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/2.1%20Black-Scholes%20PDE%20and%20sparse%20matrices.ipynb) 81 | *(PDE discretization, Implicit method, sparse matrix tutorial)* 82 | 83 | 2.2) **Exotic options** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/2.2%20Exotic%20options.ipynb) 84 | *(Binary options, Barrier options)* 85 | 86 | 2.3) **American options** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/2.3%20American%20Options.ipynb) 87 | *(PDE, Binomial method, Longstaff-Schwartz)* 88 | 89 | 3.1) **Merton Jump-Diffusion PIDE** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/3.1%20Merton%20jump-diffusion%2C%20PIDE%20method.ipynb) 90 | *(Implicit-Explicit discretization, discrete convolution, model limitations, Monte Carlo, Fourier inversion, semi-closed formula )* 91 | 92 | 3.2) **Variance Gamma PIDE** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/3.2%20Variance%20Gamma%20model%2C%20PIDE%20method.ipynb) 93 | *(approximated jump-diffusion PIDE, Monte Carlo, Fourier inversion, Comparison with Black-Scholes)* 94 | 95 | 3.3) **Normal Inverse Gaussian PIDE** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/3.3%20Pricing%20with%20the%20NIG%20Process.ipynb) 96 | *(approximated jump-diffusion PIDE, Monte Carlo, Fourier inversion, properties of the Lévy measure)* 97 | 98 | 4.1) **Pricing with transaction costs** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/4.1%20Option%20pricing%20with%20transaction%20costs.ipynb) 99 | *(Davis-Panas-Zariphopoulou model, singular control problem, HJB variational inequality, indifference pricing, binomial tree, performances)* 100 | 101 | 5.1) **Linear regression and Kalman filter** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/5.1%20Linear%20regression%20-%20Kalman%20filter.ipynb) 102 | *(market data cleaning, Linear regression methods, Kalman filter design, choice of parameters)* 103 | 104 | A.1) **Appendix: Linear equations** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/A.1%20Solution%20of%20linear%20equations.ipynb) 105 | *(LU, Jacobi, Gauss-Seidel, SOR, Thomas)* 106 | 107 | A.2) **Appendix: Code optimization** [nbviewer](https://nbviewer.ipython.org/github/cantaro86/Financial-Models-Numerical-Methods/blob/master/A.2%20Optimize%20and%20speed%20up%20the%20code.%20%28SOR%20algorithm%2C%20Cython%20and%20C%29.ipynb) 108 | *(cython, C code)* 109 | 110 | A.3) **Appendix: Review of Lévy processes theory** [github](https://github.com/cantaro86/Financial-Models-Numerical-Methods/blob/master/A.3%20Introduction%20to%20L%C3%A9vy%20processes%20and%20PIDEs.pdf) 111 | *(basic and important definitions, derivation of the pricing PIDE)* 112 | 113 | 114 | 115 | ## How to run the notebooks 116 | 117 | You have two options: 118 | 119 | 1) Install [docker](https://www.docker.com/) following the instructions in [install link](https://docs.docker.com/install/) 120 | 121 | At this point, you just need to run the script ```docker_start_notebook.py``` and you are done. 122 | This script will download the data-science docker image [scipy-notebook](https://hub.docker.com/r/jupyter/scipy-notebook), that will be used every time you run the script (the script will take about 10-15 minutes to download the image, ONLY the first time). You can also download a different image by modifying the script. For a list of images see [here](https://jupyter-docker-stacks.readthedocs.io/en/latest/using/selecting.html). 123 | 124 | 2) Clone the repository and open the notebooks using `jupyter-notebook`. 125 | If you are using an old version of python there can be compatibility problems. 126 | 127 | ```diff 128 | - Cython code needs to be compiled! 129 | ``` 130 | 131 | If you are using the data science image, you can open the shell in the notebooks directory, and run the script 132 | ```bash 133 | python docker_start_notebook.py 134 | ``` 135 | 136 | after that, copy-paste the following code into the shell: 137 | 138 | ```bash 139 | docker exec -it Numeric_Finance bash 140 | cd work/functions/cython 141 | python setup.py build_ext --inplace 142 | exit 143 | ``` 144 | (`Numeric_Finance` is the name of the docker container) 145 | 146 | If you are not using docker, just copy in the shell the following: 147 | 148 | ```bash 149 | cd functions/cython 150 | python setup.py build_ext --inplace 151 | ``` 152 | 153 | 154 | ### Enjoy! -------------------------------------------------------------------------------- /functions/Merton_pricer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Sun Aug 11 09:47:49 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | from scipy import sparse 10 | from scipy.sparse.linalg import splu 11 | from time import time 12 | import numpy as np 13 | import scipy as scp 14 | import scipy.stats as ss 15 | from scipy import signal 16 | import matplotlib.pyplot as plt 17 | from mpl_toolkits import mplot3d 18 | from matplotlib import cm 19 | from functions.BS_pricer import BS_pricer 20 | from math import factorial 21 | from functions.CF import cf_mert 22 | from functions.probabilities import Q1, Q2 23 | from functools import partial 24 | 25 | 26 | class Merton_pricer(): 27 | """ 28 | Closed Formula. 29 | Monte Carlo. 30 | Finite-difference PIDE: Explicit-implicit scheme 31 | 32 | 0 = dV/dt + (r -(1/2)sig^2 -m) dV/dx + (1/2)sig^2 d^V/dx^2 33 | + \int[ V(x+y) nu(dy) ] -(r+lam)V 34 | """ 35 | def __init__(self, Option_info, Process_info ): 36 | """ 37 | Process_info: of type Merton_process. It contains (r, sig, lam, muJ, sigJ) i.e. 38 | interest rate, diffusion coefficient, jump activity and jump distribution parameters 39 | 40 | Option_info: of type Option_param. It contains (S0,K,T) i.e. current price, strike, maturity in years 41 | """ 42 | self.r = Process_info.r # interest rate 43 | self.sig = Process_info.sig # diffusion coefficient 44 | self.lam = Process_info.lam # jump activity 45 | self.muJ = Process_info.muJ # jump mean 46 | self.sigJ = Process_info.sigJ # jump std 47 | self.exp_RV = Process_info.exp_RV # function to generate exponential Merton Random Variables 48 | 49 | self.S0 = Option_info.S0 # current price 50 | self.K = Option_info.K # strike 51 | self.T = Option_info.T # maturity in years 52 | 53 | self.price = 0 54 | self.S_vec = None 55 | self.price_vec = None 56 | self.mesh = None 57 | self.exercise = Option_info.exercise 58 | self.payoff = Option_info.payoff 59 | 60 | 61 | 62 | def payoff_f(self, S): 63 | if self.payoff == "call": 64 | Payoff = np.maximum( S - self.K, 0 ) 65 | elif self.payoff == "put": 66 | Payoff = np.maximum( self.K - S, 0 ) 67 | return Payoff 68 | 69 | 70 | 71 | def closed_formula(self): 72 | """ 73 | Merton closed formula. 74 | """ 75 | 76 | m = self.lam * (np.exp(self.muJ + (self.sigJ**2)/2) -1) # coefficient m 77 | lam2 = self.lam * np.exp(self.muJ + (self.sigJ**2)/2) 78 | 79 | tot=0 80 | for i in range(18): 81 | tot += ( np.exp(-lam2*self.T) * (lam2*self.T)**i / factorial(i) ) \ 82 | * BS_pricer.BlackScholes(self.payoff, self.S0, self.K, self.T, self.r-m+i*(self.muJ+0.5*self.sigJ**2)/self.T, 83 | np.sqrt(self.sig**2 + (i*self.sigJ**2)/self.T) ) 84 | return tot 85 | 86 | 87 | def Fourier_inversion(self): 88 | """ 89 | Price obtained by inversion of the characteristic function 90 | """ 91 | k = np.log(self.K/self.S0) # log moneyness 92 | m = self.lam * (np.exp(self.muJ + (self.sigJ**2)/2) -1) # coefficient m 93 | cf_Mert = partial(cf_mert, t=self.T, mu=( self.r - 0.5 * self.sig**2 -m ), sig=self.sig, lam=self.lam, muJ=self.muJ, sigJ=self.sigJ ) 94 | 95 | if self.payoff == "call": 96 | call = self.S0 * Q1(k, cf_Mert, np.inf) - self.K * np.exp(-self.r*self.T) * Q2(k, cf_Mert, np.inf) # pricing function 97 | return call 98 | elif self.payoff == "put": 99 | put = self.K * np.exp(-self.r*self.T) * (1 - Q2(k, cf_Mert, np.inf)) - self.S0 * (1-Q1(k, cf_Mert, np.inf)) # pricing function 100 | return put 101 | else: 102 | raise ValueError("invalid type. Set 'call' or 'put'") 103 | 104 | 105 | 106 | def MC(self, N, Err=False, Time=False): 107 | """ 108 | Merton Monte Carlo 109 | Err = return Standard Error if True 110 | Time = return execution time if True 111 | """ 112 | t_init = time() 113 | 114 | S_T = self.exp_RV( self.S0, self.T, N ) 115 | V = scp.mean( np.exp(-self.r*self.T) * self.payoff_f(S_T) ) 116 | 117 | if (Err == True): 118 | if (Time == True): 119 | elapsed = time()-t_init 120 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)), elapsed 121 | else: 122 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)) 123 | else: 124 | if (Time == True): 125 | elapsed = time()-t_init 126 | return V, elapsed 127 | else: 128 | return V 129 | 130 | 131 | 132 | def PIDE_price(self, steps, Time=False): 133 | """ 134 | steps = tuple with number of space steps and time steps 135 | payoff = "call" or "put" 136 | exercise = "European" or "American" 137 | Time = Boolean. Execution time. 138 | """ 139 | t_init = time() 140 | 141 | Nspace = steps[0] 142 | Ntime = steps[1] 143 | 144 | S_max = 6*float(self.K) 145 | S_min = float(self.K)/6 146 | x_max = np.log(S_max) 147 | x_min = np.log(S_min) 148 | 149 | dev_X = np.sqrt(self.lam * self.sigJ**2 + self.lam * self.muJ**2) 150 | 151 | dx = (x_max - x_min)/(Nspace-1) 152 | extraP = int(np.floor(5*dev_X/dx)) # extra points beyond the B.C. 153 | x = np.linspace(x_min-extraP*dx, x_max+extraP*dx, Nspace + 2*extraP) # space discretization 154 | t, dt = np.linspace(0, self.T, Ntime, retstep=True) # time discretization 155 | 156 | Payoff = self.payoff_f(np.exp(x)) 157 | offset = np.zeros(Nspace-2) 158 | V = np.zeros((Nspace + 2*extraP, Ntime)) # grid initialization 159 | 160 | if self.payoff == "call": 161 | V[:,-1] = Payoff # terminal conditions 162 | V[-extraP-1:,:] = np.exp(x[-extraP-1:]).reshape(extraP+1,1) * np.ones((extraP+1,Ntime)) - \ 163 | self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) # boundary condition 164 | V[:extraP+1,:] = 0 165 | else: 166 | V[:,-1] = Payoff 167 | V[-extraP-1:,:] = 0 168 | V[:extraP+1,:] = self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) 169 | 170 | 171 | cdf = ss.norm.cdf([np.linspace(-(extraP+1+0.5)*dx, (extraP+1+0.5)*dx, 2*(extraP+2) )], loc=self.muJ, scale=self.sigJ)[0] 172 | nu = self.lam * (cdf[1:] - cdf[:-1]) 173 | 174 | lam_appr = sum(nu) 175 | m_appr = np.array([ np.exp(i*dx)-1 for i in range(-(extraP+1), extraP+2)]) @ nu 176 | 177 | sig2 = self.sig**2 178 | dxx = dx**2 179 | a = ( (dt/2) * ( (self.r -m_appr -0.5*sig2)/dx - sig2/dxx ) ) 180 | b = ( 1 + dt * ( sig2/dxx + self.r + lam_appr) ) 181 | c = (-(dt/2) * ( (self.r -m_appr -0.5*sig2)/dx + sig2/dxx ) ) 182 | 183 | D = sparse.diags([a, b, c], [-1, 0, 1], shape=(Nspace-2, Nspace-2)).tocsc() 184 | DD = splu(D) 185 | if self.exercise=="European": 186 | for i in range(Ntime-2,-1,-1): 187 | offset[0] = a * V[extraP,i] 188 | offset[-1] = c * V[-1-extraP,i] 189 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="fft") 190 | V[extraP+1 : -extraP-1, i] = DD.solve( V_jump - offset ) 191 | elif self.exercise=="American": 192 | for i in range(Ntime-2,-1,-1): 193 | offset[0] = a * V[extraP,i] 194 | offset[-1] = c * V[-1-extraP,i] 195 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="fft") 196 | V[extraP+1 : -extraP-1, i] = np.maximum( DD.solve( V_jump - offset ), Payoff[extraP+1 : -extraP-1] ) 197 | 198 | X0 = np.log(self.S0) # current log-price 199 | self.S_vec = np.exp(x[extraP+1 : -extraP-1]) # vector of S 200 | self.price = np.interp(X0, x, V[:,0]) 201 | self.price_vec = V[extraP+1 : -extraP-1,0] 202 | self.mesh = V[extraP+1 : -extraP-1, :] 203 | 204 | if (Time == True): 205 | elapsed = time()-t_init 206 | return self.price, elapsed 207 | else: 208 | return self.price 209 | 210 | 211 | def plot(self, axis=None): 212 | if (type(self.S_vec) != np.ndarray or type(self.price_vec) != np.ndarray): 213 | self.PIDE_price((5000,4000)) 214 | 215 | plt.plot(self.S_vec, self.payoff_f(self.S_vec) , color='blue',label="Payoff") 216 | plt.plot(self.S_vec, self.price_vec, color='red',label="Merton curve") 217 | if (type(axis) == list): 218 | plt.axis(axis) 219 | plt.xlabel("S"); plt.ylabel("price"); plt.title("Merton price") 220 | plt.legend(loc='upper left') 221 | plt.show() 222 | 223 | def mesh_plt(self): 224 | if (type(self.S_vec) != np.ndarray or type(self.mesh) != np.ndarray): 225 | self.PDE_price((7000,5000)) 226 | 227 | fig = plt.figure() 228 | ax = fig.add_subplot(111, projection='3d') 229 | 230 | X, Y = np.meshgrid( np.linspace(0, self.T, self.mesh.shape[1]) , self.S_vec) 231 | ax.plot_surface(Y, X, self.mesh, cmap=cm.ocean) 232 | ax.set_title("Merton price surface") 233 | ax.set_xlabel("S"); ax.set_ylabel("t"); ax.set_zlabel("V") 234 | ax.view_init(30, -100) # this function rotates the 3d plot 235 | plt.show() 236 | -------------------------------------------------------------------------------- /functions/NIG_pricer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Fri Nov 1 12:47:00 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | from scipy import sparse 10 | from scipy.sparse.linalg import splu 11 | from time import time 12 | import numpy as np 13 | import scipy as scp 14 | from scipy import signal 15 | from scipy.integrate import quad 16 | import scipy.stats as ss 17 | import scipy.special as scps 18 | 19 | import matplotlib.pyplot as plt 20 | from mpl_toolkits import mplot3d 21 | from matplotlib import cm 22 | from functions.CF import cf_NIG 23 | from functions.probabilities import Q1, Q2 24 | from functools import partial 25 | 26 | 27 | class NIG_pricer(): 28 | """ 29 | Closed Formula. 30 | Monte Carlo. 31 | Finite-difference PIDE: Explicit-implicit scheme, with Brownian approximation 32 | 33 | 0 = dV/dt + (r -(1/2)sig^2 -w) dV/dx + (1/2)sig^2 d^V/dx^2 34 | + \int[ V(x+y) nu(dy) ] -(r+lam)V 35 | """ 36 | def __init__(self, Option_info, Process_info ): 37 | """ 38 | Process_info: of type NIG_process. It contains the interest rate r and the NIG parameters (sigma, theta, kappa) 39 | 40 | Option_info: of type Option_param. It contains (S0,K,T) i.e. current price, strike, maturity in years 41 | """ 42 | self.r = Process_info.r # interest rate 43 | self.sigma = Process_info.sigma # NIG parameter 44 | self.theta = Process_info.theta # NIG parameter 45 | self.kappa = Process_info.kappa # NIG parameter 46 | self.exp_RV = Process_info.exp_RV # function to generate exponential NIG Random Variables 47 | 48 | self.S0 = Option_info.S0 # current price 49 | self.K = Option_info.K # strike 50 | self.T = Option_info.T # maturity in years 51 | 52 | self.price = 0 53 | self.S_vec = None 54 | self.price_vec = None 55 | self.mesh = None 56 | self.exercise = Option_info.exercise 57 | self.payoff = Option_info.payoff 58 | 59 | 60 | 61 | def payoff_f(self, S): 62 | if self.payoff == "call": 63 | Payoff = np.maximum( S - self.K, 0 ) 64 | elif self.payoff == "put": 65 | Payoff = np.maximum( self.K - S, 0 ) 66 | return Payoff 67 | 68 | 69 | 70 | def Fourier_inversion(self): 71 | """ 72 | Price obtained by inversion of the characteristic function 73 | """ 74 | k = np.log(self.K/self.S0) # log moneyness 75 | w = ( 1 - np.sqrt( 1 - 2*self.theta*self.kappa -self.kappa*self.sigma**2) )/self.kappa # martingale correction 76 | 77 | cf_NIG_b = partial(cf_NIG, t=self.T, mu=(self.r-w), theta=self.theta, sigma=self.sigma, kappa=self.kappa ) 78 | 79 | if self.payoff == "call": 80 | call = self.S0 * Q1(k, cf_NIG_b, np.inf) - self.K * np.exp(-self.r*self.T) * Q2(k, cf_NIG_b, np.inf) # pricing function 81 | return call 82 | elif self.payoff == "put": 83 | put = self.K * np.exp(-self.r*self.T) * (1 - Q2(k, cf_NIG_b, np.inf)) - self.S0 * (1-Q1(k, cf_NIG_b, np.inf)) # pricing function 84 | return put 85 | else: 86 | raise ValueError("invalid type. Set 'call' or 'put'") 87 | 88 | 89 | 90 | def MC(self, N, Err=False, Time=False): 91 | """ 92 | NIG Monte Carlo 93 | Err = return Standard Error if True 94 | Time = return execution time if True 95 | """ 96 | t_init = time() 97 | 98 | S_T = self.exp_RV( self.S0, self.T, N ) 99 | V = scp.mean( np.exp(-self.r*self.T) * self.payoff_f(S_T) ) 100 | 101 | if (Err == True): 102 | if (Time == True): 103 | elapsed = time()-t_init 104 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)), elapsed 105 | else: 106 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)) 107 | else: 108 | if (Time == True): 109 | elapsed = time()-t_init 110 | return V, elapsed 111 | else: 112 | return V 113 | 114 | 115 | 116 | def NIG_measure(self, x): 117 | A = self.theta/(self.sigma**2) 118 | B = np.sqrt( self.theta**2 + self.sigma**2/self.kappa ) / self.sigma**2 119 | C = np.sqrt( self.theta**2 + self.sigma**2/self.kappa) /(np.pi*self.sigma * np.sqrt(self.kappa)) 120 | return C/np.abs(x) * np.exp(A*(x)) * scps.kv(1, B*np.abs(x) ) 121 | 122 | 123 | 124 | def PIDE_price(self, steps, Time=False): 125 | """ 126 | steps = tuple with number of space steps and time steps 127 | payoff = "call" or "put" 128 | exercise = "European" or "American" 129 | Time = Boolean. Execution time. 130 | """ 131 | t_init = time() 132 | 133 | Nspace = steps[0] 134 | Ntime = steps[1] 135 | 136 | S_max = 2000*float(self.K) 137 | S_min = float(self.K)/2000 138 | x_max = np.log(S_max) 139 | x_min = np.log(S_min) 140 | 141 | dev_X = np.sqrt(self.sigma**2 + self.theta**2 * self.kappa) # std dev NIG process 142 | 143 | dx = (x_max - x_min)/(Nspace-1) 144 | extraP = int(np.floor(7*dev_X/dx)) # extra points beyond the B.C. 145 | x = np.linspace(x_min-extraP*dx, x_max+extraP*dx, Nspace + 2*extraP) # space discretization 146 | t, dt = np.linspace(0, self.T, Ntime, retstep=True) # time discretization 147 | 148 | Payoff = self.payoff_f(np.exp(x)) 149 | offset = np.zeros(Nspace-2) 150 | V = np.zeros((Nspace + 2*extraP, Ntime)) # grid initialization 151 | 152 | if self.payoff == "call": 153 | V[:,-1] = Payoff # terminal conditions 154 | V[-extraP-1:,:] = np.exp(x[-extraP-1:]).reshape(extraP+1,1) * np.ones((extraP+1,Ntime)) - \ 155 | self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) # boundary condition 156 | V[:extraP+1,:] = 0 157 | else: 158 | V[:,-1] = Payoff 159 | V[-extraP-1:,:] = 0 160 | V[:extraP+1,:] = self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) 161 | 162 | 163 | eps = 1.5*dx # the cutoff near 0 164 | lam = quad(self.NIG_measure,-(extraP+1.5)*dx,-eps)[0] + quad(self.NIG_measure,eps,(extraP+1.5)*dx)[0] # approximated intensity 165 | 166 | int_w = lambda y: (np.exp(y)-1) * self.NIG_measure(y) 167 | int_s = lambda y: y**2 * self.NIG_measure(y) 168 | 169 | w = quad(int_w, -(extraP+1.5)*dx, -eps)[0] + quad(int_w, eps, (extraP+1.5)*dx)[0] # is the approx of w 170 | sig2 = quad(int_s, -eps, eps, points=0)[0] # the small jumps variance 171 | 172 | 173 | dxx = dx * dx 174 | a = ( (dt/2) * ( (self.r - w - 0.5*sig2)/dx - sig2/dxx ) ) 175 | b = ( 1 + dt * ( sig2/dxx + self.r + lam) ) 176 | c = (-(dt/2) * ( (self.r - w - 0.5*sig2)/dx + sig2/dxx ) ) 177 | D = sparse.diags([a, b, c], [-1, 0, 1], shape=(Nspace-2, Nspace-2)).tocsc() 178 | DD = splu(D) 179 | 180 | nu = np.zeros(2*extraP+3) # Lévy measure vector 181 | x_med = extraP+1 # middle point in nu vector 182 | x_nu = np.linspace(-(extraP+1+0.5)*dx, (extraP+1+0.5)*dx, 2*(extraP+2) ) # integration domain 183 | for i in range(len(nu)): 184 | if (i==x_med) or (i==x_med-1) or (i==x_med+1): 185 | continue 186 | nu[i] = quad(self.NIG_measure, x_nu[i], x_nu[i+1])[0] 187 | 188 | 189 | if self.exercise=="European": 190 | # Backward iteration 191 | for i in range(Ntime-2,-1,-1): 192 | offset[0] = a * V[extraP,i] 193 | offset[-1] = c * V[-1-extraP,i] 194 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="auto") 195 | V[extraP+1 : -extraP-1, i] = DD.solve( V_jump - offset ) 196 | elif self.exercise=="American": 197 | for i in range(Ntime-2,-1,-1): 198 | offset[0] = a * V[extraP,i] 199 | offset[-1] = c * V[-1-extraP,i] 200 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="auto") 201 | V[extraP+1 : -extraP-1, i] = np.maximum( DD.solve( V_jump - offset ), Payoff[extraP+1 : -extraP-1] ) 202 | 203 | X0 = np.log(self.S0) # current log-price 204 | self.S_vec = np.exp(x[extraP+1 : -extraP-1]) # vector of S 205 | self.price = np.interp(X0, x, V[:,0]) 206 | self.price_vec = V[extraP+1 : -extraP-1,0] 207 | self.mesh = V[extraP+1 : -extraP-1, :] 208 | 209 | if (Time == True): 210 | elapsed = time()-t_init 211 | return self.price, elapsed 212 | else: 213 | return self.price 214 | 215 | 216 | def plot(self, axis=None): 217 | if (type(self.S_vec) != np.ndarray or type(self.price_vec) != np.ndarray): 218 | self.PIDE_price((5000,4000)) 219 | 220 | plt.plot(self.S_vec, self.payoff_f(self.S_vec) , color='blue',label="Payoff") 221 | plt.plot(self.S_vec, self.price_vec, color='red',label="NIG curve") 222 | if (type(axis) == list): 223 | plt.axis(axis) 224 | plt.xlabel("S"); plt.ylabel("price"); plt.title("NIG price") 225 | plt.legend(loc='best') 226 | plt.show() 227 | 228 | def mesh_plt(self): 229 | if (type(self.S_vec) != np.ndarray or type(self.mesh) != np.ndarray): 230 | self.PDE_price((7000,5000)) 231 | 232 | fig = plt.figure() 233 | ax = fig.add_subplot(111, projection='3d') 234 | 235 | X, Y = np.meshgrid( np.linspace(0, self.T, self.mesh.shape[1]) , self.S_vec) 236 | ax.plot_surface(Y, X, self.mesh, cmap=cm.ocean) 237 | ax.set_title("NIG price surface") 238 | ax.set_xlabel("S"); ax.set_ylabel("t"); ax.set_zlabel("V") 239 | ax.view_init(30, -100) # this function rotates the 3d plot 240 | plt.show() 241 | 242 | 243 | 244 | 245 | -------------------------------------------------------------------------------- /functions/BS_pricer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Thu Jun 13 10:18:39 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | import numpy as np 10 | import scipy as scp 11 | from scipy.sparse.linalg import spsolve 12 | from scipy import sparse 13 | from scipy.sparse.linalg import splu 14 | import matplotlib.pyplot as plt 15 | from mpl_toolkits import mplot3d 16 | from matplotlib import cm 17 | from time import time 18 | import scipy.stats as ss 19 | from functions.Solvers import Thomas 20 | from functions.cython.cython_functions import SOR 21 | from functions.CF import cf_normal 22 | from functions.probabilities import Q1, Q2 23 | from functools import partial 24 | 25 | 26 | 27 | class BS_pricer(): 28 | """ 29 | Closed Formula. 30 | Monte Carlo. 31 | Finite-difference Black-Scholes PDE: 32 | df/dt + r df/dx + 1/2 sigma^2 d^f/dx^2 -rf = 0 33 | """ 34 | def __init__(self, Option_info, Process_info ): 35 | """ 36 | Process_info: of type Diffusion_process. It contains (r,mu, sig) i.e. interest rate, drift coefficient, diffusion coefficient 37 | 38 | Option_info: of type Option_param. It contains (S0,K,T) i.e. current price, strike, maturity in years 39 | """ 40 | self.r = Process_info.r # interest rate 41 | self.sig = Process_info.sig # diffusion coefficient 42 | self.S0 = Option_info.S0 # current price 43 | self.K = Option_info.K # strike 44 | self.T = Option_info.T # maturity in years 45 | self.exp_RV = Process_info.exp_RV # function to generate solution of GBM 46 | 47 | self.price = 0 48 | self.S_vec = None 49 | self.price_vec = None 50 | self.mesh = None 51 | self.exercise = Option_info.exercise 52 | self.payoff = Option_info.payoff 53 | 54 | 55 | def payoff_f(self, S): 56 | if self.payoff == "call": 57 | Payoff = np.maximum( S - self.K, 0 ) 58 | elif self.payoff == "put": 59 | Payoff = np.maximum( self.K - S, 0 ) 60 | return Payoff 61 | 62 | 63 | @staticmethod 64 | def BlackScholes(payoff='call', S0=100., K=100., T=1., r=0.1, sigma=0.2 ): 65 | """ Black Scholes closed formula: 66 | payoff: call or put. 67 | S0: float. initial stock/index level. 68 | K: float strike price. 69 | T: float maturity (in year fractions). 70 | r: float constant risk-free short rate. 71 | sigma: volatility factor in diffusion term. """ 72 | 73 | d1 = (np.log(S0/K) + (r + sigma**2 / 2) * T) / (sigma * np.sqrt(T)) 74 | d2 = (np.log(S0/K) + (r - sigma**2 / 2) * T) / (sigma * np.sqrt(T)) 75 | 76 | if payoff=="call": 77 | return S0 * ss.norm.cdf( d1 ) - K * np.exp(-r * T) * ss.norm.cdf( d2 ) 78 | elif payoff=="put": 79 | return K * np.exp(-r * T) * ss.norm.cdf( -d2 ) - S0 * ss.norm.cdf( -d1 ) 80 | else: 81 | raise ValueError("invalid type. Set 'call' or 'put'") 82 | 83 | 84 | def closed_formula(self): 85 | """ 86 | Black Scholes closed formula: 87 | """ 88 | d1 = (np.log(self.S0/self.K) + (self.r + self.sig**2 / 2) * self.T) / (self.sig * np.sqrt(self.T)) 89 | d2 = (np.log(self.S0/self.K) + (self.r - self.sig**2 / 2) * self.T) / (self.sig * np.sqrt(self.T)) 90 | 91 | if self.payoff=="call": 92 | return self.S0 * ss.norm.cdf( d1 ) - self.K * np.exp(-self.r * self.T) * ss.norm.cdf( d2 ) 93 | elif self.payoff=="put": 94 | return self.K * np.exp(-self.r * self.T) * ss.norm.cdf( -d2 ) - self.S0 * ss.norm.cdf( -d1 ) 95 | else: 96 | raise ValueError("invalid type. Set 'call' or 'put'") 97 | 98 | 99 | 100 | def Fourier_inversion(self): 101 | """ 102 | Price obtained by inversion of the characteristic function 103 | """ 104 | k = np.log(self.K/self.S0) 105 | cf_GBM = partial(cf_normal, mu=( self.r - 0.5 * self.sig**2 )*self.T, sig=self.sig*np.sqrt(self.T)) # function binding 106 | 107 | if self.payoff == "call": 108 | call = self.S0 * Q1(k, cf_GBM, np.inf) - self.K * np.exp(-self.r*self.T) * Q2(k, cf_GBM, np.inf) # pricing function 109 | return call 110 | elif self.payoff == "put": 111 | put = self.K * np.exp(-self.r*self.T) * (1 - Q2(k, cf_GBM, np.inf)) - self.S0 * (1-Q1(k, cf_GBM, np.inf)) # pricing function 112 | return put 113 | else: 114 | raise ValueError("invalid type. Set 'call' or 'put'") 115 | 116 | 117 | 118 | def MC(self, N, Err=False, Time=False): 119 | """ 120 | BS Monte Carlo 121 | Err = return Standard Error if True 122 | Time = return execution time if True 123 | """ 124 | t_init = time() 125 | 126 | S_T = self.exp_RV( self.S0, self.T, N ) 127 | V = scp.mean( np.exp(-self.r*self.T) * self.payoff_f(S_T) ) 128 | 129 | if (Err == True): 130 | if (Time == True): 131 | elapsed = time()-t_init 132 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)), elapsed 133 | else: 134 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)) 135 | else: 136 | if (Time == True): 137 | elapsed = time()-t_init 138 | return V, elapsed 139 | else: 140 | return V 141 | 142 | 143 | 144 | def PDE_price(self, steps, Time=False, solver="splu"): 145 | """ 146 | steps = tuple with number of space steps and time steps 147 | payoff = "call" or "put" 148 | exercise = "European" or "American" 149 | Time = Boolean. Execution time. 150 | Solver = spsolve or splu or Thomas or SOR 151 | """ 152 | t_init = time() 153 | 154 | Nspace = steps[0] 155 | Ntime = steps[1] 156 | 157 | S_max = 6*float(self.K) 158 | S_min = float(self.K)/6 159 | x_max = np.log(S_max) 160 | x_min = np.log(S_min) 161 | x0 = np.log(self.S0) # current log-price 162 | 163 | x, dx = np.linspace(x_min, x_max, Nspace, retstep=True) 164 | t, dt = np.linspace(0, self.T, Ntime, retstep=True) 165 | 166 | self.S_vec = np.exp(x) # vector of S 167 | Payoff = self.payoff_f(self.S_vec) 168 | 169 | V = np.zeros((Nspace,Ntime)) 170 | if self.payoff == "call": 171 | V[:,-1] = Payoff 172 | V[-1,:] = np.exp(x_max) - self.K * np.exp(-self.r* t[::-1] ) 173 | V[0,:] = 0 174 | else: 175 | V[:,-1] = Payoff 176 | V[-1,:] = 0 177 | V[0,:] = self.K * np.exp(-self.r* t[::-1] ) 178 | 179 | sig2 = self.sig**2 180 | dxx = dx**2 181 | a = ( (dt/2) * ( (self.r-0.5*sig2)/dx - sig2/dxx ) ) 182 | b = ( 1 + dt * ( sig2/dxx + self.r ) ) 183 | c = (-(dt/2) * ( (self.r-0.5*sig2)/dx + sig2/dxx ) ) 184 | 185 | D = sparse.diags([a, b, c], [-1, 0, 1], shape=(Nspace-2, Nspace-2)).tocsc() 186 | 187 | offset = np.zeros(Nspace-2) 188 | 189 | 190 | if solver == "spsolve": 191 | if self.exercise=="European": 192 | for i in range(Ntime-2,-1,-1): 193 | offset[0] = a * V[0,i] 194 | offset[-1] = c * V[-1,i] 195 | V[1:-1,i] = spsolve( D, (V[1:-1,i+1] - offset) ) 196 | elif self.exercise=="American": 197 | for i in range(Ntime-2,-1,-1): 198 | offset[0] = a * V[0,i] 199 | offset[-1] = c * V[-1,i] 200 | V[1:-1,i] = np.maximum( spsolve( D, (V[1:-1,i+1] - offset) ), Payoff[1:-1]) 201 | elif solver == "Thomas": 202 | if self.exercise=="European": 203 | for i in range(Ntime-2,-1,-1): 204 | offset[0] = a * V[0,i] 205 | offset[-1] = c * V[-1,i] 206 | V[1:-1,i] = Thomas( D, (V[1:-1,i+1] - offset) ) 207 | elif self.exercise=="American": 208 | for i in range(Ntime-2,-1,-1): 209 | offset[0] = a * V[0,i] 210 | offset[-1] = c * V[-1,i] 211 | V[1:-1,i] = np.maximum( Thomas( D, (V[1:-1,i+1] - offset) ), Payoff[1:-1]) 212 | elif solver == "SOR": 213 | if self.exercise=="European": 214 | for i in range(Ntime-2,-1,-1): 215 | offset[0] = a * V[0,i] 216 | offset[-1] = c * V[-1,i] 217 | V[1:-1,i] = SOR( a,b,c, (V[1:-1,i+1] - offset), w=1.68, eps=1e-10, N_max=600 ) 218 | elif self.exercise=="American": 219 | for i in range(Ntime-2,-1,-1): 220 | offset[0] = a * V[0,i] 221 | offset[-1] = c * V[-1,i] 222 | V[1:-1,i] = np.maximum( SOR( a,b,c, (V[1:-1,i+1] - offset), w=1.68, eps=1e-10, N_max=600 ), Payoff[1:-1]) 223 | elif solver == "splu": 224 | DD = splu(D) 225 | if self.exercise=="European": 226 | for i in range(Ntime-2,-1,-1): 227 | offset[0] = a * V[0,i] 228 | offset[-1] = c * V[-1,i] 229 | V[1:-1,i] = DD.solve( V[1:-1,i+1] - offset ) 230 | elif self.exercise=="American": 231 | for i in range(Ntime-2,-1,-1): 232 | offset[0] = a * V[0,i] 233 | offset[-1] = c * V[-1,i] 234 | V[1:-1,i] = np.maximum( DD.solve( V[1:-1,i+1] - offset ), Payoff[1:-1]) 235 | else: 236 | raise ValueError("Solver is splu, spsolve, SOR or Thomas") 237 | 238 | self.price = np.interp(x0, x, V[:,0]) 239 | self.price_vec = V[:,0] 240 | self.mesh = V 241 | 242 | if (Time == True): 243 | elapsed = time()-t_init 244 | return self.price, elapsed 245 | else: 246 | return self.price 247 | 248 | 249 | 250 | def plot(self, axis=None): 251 | if (type(self.S_vec) != np.ndarray or type(self.price_vec) != np.ndarray): 252 | self.PDE_price((7000,5000)) 253 | #print("run the PDE_price method") 254 | #return 255 | 256 | plt.plot(self.S_vec, self.payoff_f(self.S_vec) , color='blue',label="Payoff") 257 | plt.plot(self.S_vec, self.price_vec, color='red',label="BS curve") 258 | if (type(axis) == list): 259 | plt.axis(axis) 260 | plt.xlabel("S") 261 | plt.ylabel("price") 262 | plt.title("Black Scholes price") 263 | plt.legend(loc='upper left') 264 | plt.show() 265 | 266 | 267 | def mesh_plt(self): 268 | if (type(self.S_vec) != np.ndarray or type(self.mesh) != np.ndarray): 269 | self.PDE_price((7000,5000)) 270 | 271 | fig = plt.figure() 272 | ax = fig.add_subplot(111, projection='3d') 273 | 274 | X, Y = np.meshgrid( np.linspace(0, self.T, self.mesh.shape[1]) , self.S_vec) 275 | ax.plot_surface(Y, X, self.mesh, cmap=cm.ocean) 276 | ax.set_title("BS price surface") 277 | ax.set_xlabel("S"); ax.set_ylabel("t"); ax.set_zlabel("V") 278 | ax.view_init(30, -100) # this function rotates the 3d plot 279 | plt.show() 280 | 281 | 282 | def LSM(self, N=10000, paths=10000, order=2): 283 | """ 284 | Longstaff-Schwartz Method for pricing American options 285 | 286 | N = number of time steps 287 | paths = number of generated paths 288 | order = order of the polynomial for the regression 289 | """ 290 | 291 | if self.payoff!="put": 292 | raise ValueError("invalid type. Set 'call' or 'put'") 293 | 294 | dt = self.T/(N-1) # time interval 295 | df = np.exp(-self.r * dt) # discount factor per time time interval 296 | 297 | X0 = np.zeros((paths,1)) 298 | increments = ss.norm.rvs(loc=(self.r-self.sig**2/2)*dt, scale=np.sqrt(dt)*self.sig, size=(paths,N-1)) 299 | X = np.concatenate((X0,increments), axis=1).cumsum(1) 300 | S = self.S0 * np.exp(X) 301 | 302 | H = np.maximum(self.K - S, 0) # intrinsic values for put option 303 | V = np.zeros_like(H) # value matrix 304 | V[:,-1] = H[:,-1] 305 | 306 | # Valuation by LS Method 307 | for t in range(N-2, 0, -1): 308 | good_paths = H[:,t] > 0 309 | rg = np.polyfit( S[good_paths, t], V[good_paths, t+1] * df, 2) # polynomial regression 310 | C = np.polyval( rg, S[good_paths,t] ) # evaluation of regression 311 | 312 | exercise = np.zeros( len(good_paths), dtype=bool) 313 | exercise[good_paths] = H[good_paths,t] > C 314 | 315 | V[exercise,t] = H[exercise,t] 316 | V[exercise,t+1:] = 0 317 | discount_path = (V[:,t] == 0) 318 | V[discount_path,t] = V[discount_path,t+1] * df 319 | 320 | V0 = np.mean(V[:,1]) * df # 321 | return V0 322 | -------------------------------------------------------------------------------- /functions/VG_pricer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Mon Aug 12 18:47:05 2019 5 | 6 | @author: cantaro86 7 | """ 8 | 9 | from scipy import sparse 10 | from scipy.sparse.linalg import splu 11 | from time import time 12 | import numpy as np 13 | import scipy as scp 14 | from scipy import signal 15 | from scipy.integrate import quad 16 | import scipy.stats as ss 17 | import scipy.special as scps 18 | 19 | import matplotlib.pyplot as plt 20 | from mpl_toolkits import mplot3d 21 | from matplotlib import cm 22 | from functions.CF import cf_VG 23 | from functions.probabilities import Q1, Q2 24 | from functools import partial 25 | 26 | 27 | class VG_pricer(): 28 | """ 29 | Closed Formula. 30 | Monte Carlo. 31 | Finite-difference PIDE: Explicit-implicit scheme, with Brownian approximation 32 | 33 | 0 = dV/dt + (r -(1/2)sig^2 -w) dV/dx + (1/2)sig^2 d^V/dx^2 34 | + \int[ V(x+y) nu(dy) ] -(r+lam)V 35 | """ 36 | def __init__(self, Option_info, Process_info ): 37 | """ 38 | Process_info: of type VG_process. It contains the interest rate r and the VG parameters (sigma, theta, kappa) 39 | 40 | Option_info: of type Option_param. It contains (S0,K,T) i.e. current price, strike, maturity in years 41 | """ 42 | self.r = Process_info.r # interest rate 43 | self.sigma = Process_info.sigma # VG parameter 44 | self.theta = Process_info.theta # VG parameter 45 | self.kappa = Process_info.kappa # VG parameter 46 | self.exp_RV = Process_info.exp_RV # function to generate exponential VG Random Variables 47 | 48 | self.S0 = Option_info.S0 # current price 49 | self.K = Option_info.K # strike 50 | self.T = Option_info.T # maturity in years 51 | 52 | self.price = 0 53 | self.S_vec = None 54 | self.price_vec = None 55 | self.mesh = None 56 | self.exercise = Option_info.exercise 57 | self.payoff = Option_info.payoff 58 | 59 | 60 | 61 | def payoff_f(self, S): 62 | if self.payoff == "call": 63 | Payoff = np.maximum( S - self.K, 0 ) 64 | elif self.payoff == "put": 65 | Payoff = np.maximum( self.K - S, 0 ) 66 | return Payoff 67 | 68 | 69 | 70 | def closed_formula(self): 71 | """ 72 | VG closed formula. Put is obtained by put/call parity. 73 | """ 74 | 75 | def Psy(a,b,g): 76 | f = lambda u: ss.norm.cdf(a/np.sqrt(u) + b*np.sqrt(u)) * u**(g-1) * np.exp(-u) / scps.gamma(g) 77 | result = quad( f, 0, np.inf ) 78 | return result[0] 79 | 80 | # Ugly parameters 81 | xi = - self.theta / self.sigma**2 82 | s = self.sigma / np.sqrt( 1+ ((self.theta/self.sigma)**2) * (self.kappa/2) ) 83 | alpha = xi * s 84 | 85 | c1 = self.kappa/2 * (alpha + s)**2 86 | c2 = self.kappa/2 * alpha**2 87 | d = 1/s * ( np.log(self.S0/self.K) + self.r*self.T + self.T/self.kappa * np.log( (1-c1)/(1-c2) ) ) 88 | 89 | # Closed formula 90 | call = self.S0 * Psy( d * np.sqrt((1-c1)/self.kappa) , (alpha+s) * np.sqrt(self.kappa/(1-c1)) , self.T/self.kappa ) - \ 91 | self.K * np.exp(-self.r*self.T) * Psy( d * np.sqrt((1-c2)/self.kappa) , \ 92 | (alpha) * np.sqrt(self.kappa/(1-c2)) , self.T/self.kappa ) 93 | 94 | if self.payoff == "call": 95 | return call 96 | elif self.payoff == "put": 97 | return call - self.S0 + self.K * np.exp(-self.r * self.T) 98 | else: 99 | raise ValueError("invalid type. Set 'call' or 'put'") 100 | 101 | 102 | def Fourier_inversion(self): 103 | """ 104 | Price obtained by inversion of the characteristic function 105 | """ 106 | k = np.log(self.K/self.S0) # log moneyness 107 | w = -np.log(1 - self.theta * self.kappa - self.kappa/2 * self.sigma**2 ) /self.kappa # coefficient w 108 | cf_VG_b = partial(cf_VG, t=self.T, mu=(self.r-w), theta=self.theta, sigma=self.sigma, kappa=self.kappa ) 109 | 110 | right_lim = 5000 # using np.inf may create warnings 111 | if self.payoff == "call": 112 | call = self.S0 * Q1(k, cf_VG_b, right_lim) - self.K * np.exp(-self.r*self.T) * Q2(k, cf_VG_b, right_lim) # pricing function 113 | return call 114 | elif self.payoff == "put": 115 | put = self.K * np.exp(-self.r*self.T) * (1 - Q2(k, cf_VG_b, right_lim)) - self.S0 * (1-Q1(k, cf_VG_b, right_lim)) # pricing function 116 | return put 117 | else: 118 | raise ValueError("invalid type. Set 'call' or 'put'") 119 | 120 | 121 | 122 | def MC(self, N, Err=False, Time=False): 123 | """ 124 | Variance Gamma Monte Carlo 125 | Err = return Standard Error if True 126 | Time = return execution time if True 127 | """ 128 | t_init = time() 129 | 130 | S_T = self.exp_RV( self.S0, self.T, N ) 131 | V = scp.mean( np.exp(-self.r*self.T) * self.payoff_f(S_T) ) 132 | 133 | if (Err == True): 134 | if (Time == True): 135 | elapsed = time()-t_init 136 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)), elapsed 137 | else: 138 | return V, ss.sem(np.exp(-self.r*self.T) * self.payoff_f(S_T)) 139 | else: 140 | if (Time == True): 141 | elapsed = time()-t_init 142 | return V, elapsed 143 | else: 144 | return V 145 | 146 | 147 | 148 | def PIDE_price(self, steps, Time=False): 149 | """ 150 | steps = tuple with number of space steps and time steps 151 | payoff = "call" or "put" 152 | exercise = "European" or "American" 153 | Time = Boolean. Execution time. 154 | """ 155 | t_init = time() 156 | 157 | Nspace = steps[0] 158 | Ntime = steps[1] 159 | 160 | S_max = 6*float(self.K) 161 | S_min = float(self.K)/6 162 | x_max = np.log(S_max) 163 | x_min = np.log(S_min) 164 | 165 | dev_X = np.sqrt(self.sigma**2 + self.theta**2 * self.kappa) # std dev VG process 166 | 167 | dx = (x_max - x_min)/(Nspace-1) 168 | extraP = int(np.floor(5*dev_X/dx)) # extra points beyond the B.C. 169 | x = np.linspace(x_min-extraP*dx, x_max+extraP*dx, Nspace + 2*extraP) # space discretization 170 | t, dt = np.linspace(0, self.T, Ntime, retstep=True) # time discretization 171 | 172 | Payoff = self.payoff_f(np.exp(x)) 173 | offset = np.zeros(Nspace-2) 174 | V = np.zeros((Nspace + 2*extraP, Ntime)) # grid initialization 175 | 176 | if self.payoff == "call": 177 | V[:,-1] = Payoff # terminal conditions 178 | V[-extraP-1:,:] = np.exp(x[-extraP-1:]).reshape(extraP+1,1) * np.ones((extraP+1,Ntime)) - \ 179 | self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) # boundary condition 180 | V[:extraP+1,:] = 0 181 | else: 182 | V[:,-1] = Payoff 183 | V[-extraP-1:,:] = 0 184 | V[:extraP+1,:] = self.K * np.exp(-self.r* t[::-1] ) * np.ones((extraP+1,Ntime)) 185 | 186 | 187 | A = self.theta/(self.sigma**2) 188 | B = np.sqrt( self.theta**2 + 2*self.sigma**2/self.kappa ) / self.sigma**2 189 | levy_m = lambda y: np.exp( A*y - B*np.abs(y) ) / (self.kappa*np.abs(y)) # Levy measure VG 190 | 191 | eps = 1.5*dx # the cutoff near 0 192 | lam = quad(levy_m,-(extraP+1.5)*dx,-eps)[0] + quad(levy_m,eps,(extraP+1.5)*dx)[0] # approximated intensity 193 | 194 | int_w = lambda y: (np.exp(y)-1) * levy_m(y) 195 | int_s = lambda y: np.abs(y) * np.exp( A*y - B*np.abs(y) ) / self.kappa # avoid division by zero 196 | 197 | w = quad(int_w, -(extraP+1.5)*dx, -eps)[0] + quad(int_w, eps, (extraP+1.5)*dx)[0] # is the approx of omega 198 | 199 | sig2 = quad(int_s,-eps,eps)[0] # the small jumps variance 200 | 201 | 202 | dxx = dx * dx 203 | a = ( (dt/2) * ( (self.r - w - 0.5*sig2)/dx - sig2/dxx ) ) 204 | b = ( 1 + dt * ( sig2/dxx + self.r + lam) ) 205 | c = (-(dt/2) * ( (self.r - w - 0.5*sig2)/dx + sig2/dxx ) ) 206 | D = sparse.diags([a, b, c], [-1, 0, 1], shape=(Nspace-2, Nspace-2)).tocsc() 207 | DD = splu(D) 208 | 209 | nu = np.zeros(2*extraP+3) # Lévy measure vector 210 | x_med = extraP+1 # middle point in nu vector 211 | x_nu = np.linspace(-(extraP+1+0.5)*dx, (extraP+1+0.5)*dx, 2*(extraP+2) ) # integration domain 212 | for i in range(len(nu)): 213 | if (i==x_med) or (i==x_med-1) or (i==x_med+1): 214 | continue 215 | nu[i] = quad(levy_m, x_nu[i], x_nu[i+1])[0] 216 | 217 | 218 | if self.exercise=="European": 219 | # Backward iteration 220 | for i in range(Ntime-2,-1,-1): 221 | offset[0] = a * V[extraP,i] 222 | offset[-1] = c * V[-1-extraP,i] 223 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="auto") 224 | V[extraP+1 : -extraP-1, i] = DD.solve( V_jump - offset ) 225 | elif self.exercise=="American": 226 | for i in range(Ntime-2,-1,-1): 227 | offset[0] = a * V[extraP,i] 228 | offset[-1] = c * V[-1-extraP,i] 229 | V_jump = V[extraP+1 : -extraP-1, i+1] + dt * signal.convolve(V[:,i+1],nu[::-1],mode="valid",method="auto") 230 | V[extraP+1 : -extraP-1, i] = np.maximum( DD.solve( V_jump - offset ), Payoff[extraP+1 : -extraP-1] ) 231 | 232 | X0 = np.log(self.S0) # current log-price 233 | self.S_vec = np.exp(x[extraP+1 : -extraP-1]) # vector of S 234 | self.price = np.interp(X0, x, V[:,0]) 235 | self.price_vec = V[extraP+1 : -extraP-1,0] 236 | self.mesh = V[extraP+1 : -extraP-1, :] 237 | 238 | if (Time == True): 239 | elapsed = time()-t_init 240 | return self.price, elapsed 241 | else: 242 | return self.price 243 | 244 | 245 | def plot(self, axis=None): 246 | if (type(self.S_vec) != np.ndarray or type(self.price_vec) != np.ndarray): 247 | self.PIDE_price((5000,4000)) 248 | 249 | plt.plot(self.S_vec, self.payoff_f(self.S_vec) , color='blue',label="Payoff") 250 | plt.plot(self.S_vec, self.price_vec, color='red',label="VG curve") 251 | if (type(axis) == list): 252 | plt.axis(axis) 253 | plt.xlabel("S"); plt.ylabel("price"); plt.title("VG price") 254 | plt.legend(loc='upper left') 255 | plt.show() 256 | 257 | def mesh_plt(self): 258 | if (type(self.S_vec) != np.ndarray or type(self.mesh) != np.ndarray): 259 | self.PDE_price((7000,5000)) 260 | 261 | fig = plt.figure() 262 | ax = fig.add_subplot(111, projection='3d') 263 | 264 | X, Y = np.meshgrid( np.linspace(0, self.T, self.mesh.shape[1]) , self.S_vec) 265 | ax.plot_surface(Y, X, self.mesh, cmap=cm.ocean) 266 | ax.set_title("VG price surface") 267 | ax.set_xlabel("S"); ax.set_ylabel("t"); ax.set_zlabel("V") 268 | ax.view_init(30, -100) # this function rotates the 3d plot 269 | plt.show() 270 | 271 | 272 | 273 | def closed_formula_wrong(self): 274 | """ 275 | VG closed formula. This implementation seems correct, BUT IT DOES NOT WORK!! 276 | Here I use the closed formula of Carr,Madan,Chang 1998. With scps.kv, a modified Bessel function of second kind. 277 | You can try to run it, but the output is slightly different from expected. 278 | """ 279 | def Phi(alpha,beta,gamm,x,y): 280 | 281 | f = lambda u: u**(alpha-1) * (1-u)**(gamm-alpha-1) * (1-u*x)**(-beta) * np.exp(u*y) 282 | result = quad(f, 0.00000001, 0.99999999) 283 | return ( scps.gamma(gamm) / (scps.gamma(alpha)*scps.gamma(gamm - alpha)) ) * result[0] 284 | 285 | def Psy(a,b,g): 286 | 287 | c= np.abs(a) * np.sqrt(2+b**2) 288 | u= b / np.sqrt(2+b**2) 289 | 290 | value = ( c**(g+0.5) * np.exp(np.sign(a)*c) * (1+u)**g ) / ( np.sqrt(2*np.pi) * g * scps.gamma(g) ) * \ 291 | scps.kv(g+0.5 ,c) * Phi( g,1-g,1+g, (1+u)/2, -np.sign(a)*c*(1+u) ) - \ 292 | np.sign(a) * ( c**(g+0.5) * np.exp(np.sign(a)*c) * (1+u)**(1+g) ) / ( np.sqrt(2*np.pi) * (g+1) * scps.gamma(g) ) *\ 293 | scps.kv(g-0.5 ,c) * Phi( g+1,1-g,2+g, (1+u)/2, -np.sign(a)*c*(1+u) ) + \ 294 | np.sign(a) * ( c**(g+0.5) * np.exp(np.sign(a)*c) * (1+u)**(1+g) ) / ( np.sqrt(2*np.pi) * (g+1) * scps.gamma(g) ) *\ 295 | scps.kv(g-0.5 ,c) * Phi( g,1-g,1+g, (1+u)/2, -np.sign(a)*c*(1+u) ) 296 | return value 297 | 298 | # Ugly parameters 299 | xi = - self.theta / self.sigma**2 300 | s = self.sigma / np.sqrt( 1+ ((self.theta/self.sigma)**2) * (self.kappa/2) ) 301 | alpha = xi * s 302 | 303 | c1 = self.kappa/2 * (alpha + s)**2 304 | c2 = self.kappa/2 * alpha**2 305 | d = 1/s * ( np.log(self.S0/self.K) + self.r*self.T + self.T/self.kappa * np.log( (1-c1)/(1-c2) ) ) 306 | 307 | # Closed formula 308 | call = self.S0 * Psy( d * np.sqrt((1-c1)/self.kappa) , (alpha+s) * np.sqrt(self.kappa/(1-c1)) , self.T/self.kappa ) - \ 309 | self.K * np.exp(-self.r*self.T) * Psy( d * np.sqrt((1-c2)/self.kappa) , \ 310 | (alpha) * np.sqrt(self.kappa/(1-c2)) , self.T/self.kappa ) 311 | 312 | return call 313 | 314 | -------------------------------------------------------------------------------- /A.2 Optimize and speed up the code. (SOR algorithm, Cython and C).ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# How to optimize the code?\n", 8 | "\n", 9 | "In this notebook I want to show how to write efficient code and how cython and C code can help to improve the speed. \n", 10 | "I decided to consider as example the SOR algorithm. Here we can see how the algorithm presented in the Notebook **A.1 Solution of linear equations** can be modified for our specific needs (i.e. solving PDEs). \n", 11 | "\n", 12 | "Again, if you are curious about the SOR and want to know more, have a look at the wiki page [link](https://en.wikipedia.org/wiki/Successive_over-relaxation).\n", 13 | "\n", 14 | "## Contents\n", 15 | " - [Python implelentation](#sec1)\n", 16 | " - [Cython](#sec2)\n", 17 | " - [C code](#sec3)\n", 18 | " - [BS python vs C](#sec3.1) " 19 | ] 20 | }, 21 | { 22 | "cell_type": "code", 23 | "execution_count": 1, 24 | "metadata": {}, 25 | "outputs": [], 26 | "source": [ 27 | "import os\n", 28 | "import subprocess\n", 29 | "import numpy as np\n", 30 | "import scipy as scp\n", 31 | "from scipy.linalg import norm\n", 32 | "from functions.Solvers import SOR, SOR2\n", 33 | "%load_ext cython\n", 34 | "import Cython" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 2, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "N = 3000\n", 44 | "aa = 2; bb = 10; cc = 5\n", 45 | "A = np.diag(aa * np.ones(N-1), -1) + np.diag(bb * np.ones(N), 0) + np.diag(cc * np.ones(N-1), 1)\n", 46 | "x = 2 * np.ones(N)\n", 47 | "b = A@x" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "metadata": {}, 53 | "source": [ 54 | "Here we use a tridiagonal matrix A \n", 55 | "\n", 56 | "$$ \\left(\n", 57 | "\\begin{array}{ccccc}\n", 58 | "bb & cc & 0 & \\cdots & 0 \\\\\n", 59 | "aa & bb & cc & 0 & 0 \\\\\n", 60 | "0 & \\ddots & \\ddots & \\ddots & 0 \\\\\n", 61 | "\\vdots & 0 & aa & bb & cc \\\\\n", 62 | "0 & 0 & 0 & aa & bb \\\\\n", 63 | "\\end{array}\n", 64 | "\\right) $$\n", 65 | "\n", 66 | "with equal elements in the three diagonals: \n", 67 | "\n", 68 | "$$ aa = 2, \\quad bb = 10, \\quad cc = 5 $$\n", 69 | "\n", 70 | "This is the case of the Black-Scholes equation (in log-variables). \n", 71 | "The matrix A is quite big because we want to test the performances of the algorithms.\n", 72 | "\n", 73 | "The linear system is always the same: \n", 74 | "\n", 75 | "$$ A x = b$$\n", 76 | "\n", 77 | "For simplicity I chose $x = [2,...,2]$. " 78 | ] 79 | }, 80 | { 81 | "cell_type": "markdown", 82 | "metadata": {}, 83 | "source": [ 84 | "\n", 85 | "## Python implementation\n", 86 | "\n", 87 | "I wrote two functions to implement the SOR algorithm with the aim of solving PDEs. \n", 88 | " - ```SOR``` uses matrix multiplications. The code is the same presented in the notebook **A1**: First it creates the matrices D,U,L (if A is sparse, it is converted into a numpy.array). Then it iterates the solutions until convergence. \n", 89 | " - ```SOR2``` iterates over all components of $x$ . It does not perform matrix multiplications but it considers each component of $x$ for the computations. \n", 90 | "The algorithm is the following: \n", 91 | "\n", 92 | "```python\n", 93 | " x0 = np.ones_like(b, dtype=np.float64) # initial guess\n", 94 | " x_new = np.ones_like(x0) # new solution\n", 95 | " \n", 96 | " for k in range(1,N_max+1): # iteration until convergence\n", 97 | " for i in range(N): # iteration over all the rows\n", 98 | " S = 0\n", 99 | " for j in range(N): # iteration over the columns\n", 100 | " if j != i:\n", 101 | " S += A[i,j]*x_new[j]\n", 102 | " x_new[i] = (1-w)*x_new[i] + (w/A[i,i]) * (b[i] - S) \n", 103 | " \n", 104 | " if norm(x_new - x0) < eps: # check convergence\n", 105 | " return x_new\n", 106 | " x0 = x_new.copy() # updates the solution \n", 107 | " if k==N_max:\n", 108 | " print(\"Fail to converge in {} iterations\".format(k))\n", 109 | "```\n", 110 | "This algorithm is taken from the SOR wiki [page](https://en.wikipedia.org/wiki/Successive_over-relaxation) and it is equivalent to the algorithm presented in the notebook **A1**.\n", 111 | "\n", 112 | "Let us see how fast they are: (well... how **slow** they are... be ready to wait about 6 minutes)" 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 3, 118 | "metadata": {}, 119 | "outputs": [ 120 | { 121 | "name": "stdout", 122 | "output_type": "stream", 123 | "text": [ 124 | "CPU times: user 10.2 s, sys: 15.7 s, total: 25.9 s\n", 125 | "Wall time: 8.33 s\n" 126 | ] 127 | }, 128 | { 129 | "data": { 130 | "text/plain": [ 131 | "array([2., 2., 2., ..., 2., 2., 2.])" 132 | ] 133 | }, 134 | "execution_count": 3, 135 | "metadata": {}, 136 | "output_type": "execute_result" 137 | } 138 | ], 139 | "source": [ 140 | "%%time\n", 141 | "SOR(A,b)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": 4, 147 | "metadata": {}, 148 | "outputs": [ 149 | { 150 | "name": "stdout", 151 | "output_type": "stream", 152 | "text": [ 153 | "CPU times: user 6min 23s, sys: 560 ms, total: 6min 24s\n", 154 | "Wall time: 6min 24s\n" 155 | ] 156 | }, 157 | { 158 | "data": { 159 | "text/plain": [ 160 | "array([2., 2., 2., ..., 2., 2., 2.])" 161 | ] 162 | }, 163 | "execution_count": 4, 164 | "metadata": {}, 165 | "output_type": "execute_result" 166 | } 167 | ], 168 | "source": [ 169 | "%%time\n", 170 | "SOR2(A,b)" 171 | ] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "metadata": {}, 176 | "source": [ 177 | "## TOO BAD!\n", 178 | "\n", 179 | "The second algorithm is very bad. There is an immediate improvement to do: \n", 180 | "We are working with a **tridiagonal matrix**. It means that all the elements not on the three diagonals are zero. The first piece of code to modify is OBVIOUSLY this:\n", 181 | "```python\n", 182 | "for j in range(N): # iteration over the columns\n", 183 | " if j != i:\n", 184 | " S += A[i,j]*x_new[j]\n", 185 | "``` \n", 186 | "There is no need to sum zero elements. \n", 187 | "Let us consider the new function:" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": 5, 193 | "metadata": {}, 194 | "outputs": [], 195 | "source": [ 196 | "def SOR3(A, b, w=1, eps=1e-10, N_max = 100):\n", 197 | " N = len(b)\n", 198 | " x0 = np.ones_like(b, dtype=np.float64) # initial guess\n", 199 | " x_new = np.ones_like(x0) # new solution\n", 200 | " for k in range(1,N_max+1):\n", 201 | " for i in range(N):\n", 202 | " if (i==0): # new code start \n", 203 | " S = A[0,1] * x_new[1]\n", 204 | " elif (i==N-1):\n", 205 | " S = A[N-1,N-2] * x_new[N-2]\n", 206 | " else:\n", 207 | " S = A[i,i-1] * x_new[i-1] + A[i,i+1] * x_new[i+1]\n", 208 | " # new code end \n", 209 | " x_new[i] = (1-w)*x_new[i] + (w/A[i,i]) * (b[i] - S) \n", 210 | " if norm(x_new - x0) < eps:\n", 211 | " return x_new\n", 212 | " x0 = x_new.copy()\n", 213 | " if k==N_max:\n", 214 | " print(\"Fail to converge in {} iterations\".format(k))" 215 | ] 216 | }, 217 | { 218 | "cell_type": "code", 219 | "execution_count": 6, 220 | "metadata": {}, 221 | "outputs": [ 222 | { 223 | "name": "stdout", 224 | "output_type": "stream", 225 | "text": [ 226 | "571 ms ± 12.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 227 | ] 228 | } 229 | ], 230 | "source": [ 231 | "%%timeit\n", 232 | "SOR3(A,b)" 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "metadata": {}, 238 | "source": [ 239 | "### OK ... it was easy!\n", 240 | "\n", 241 | "But wait a second... if all the elements in the three diagonals are equal, do we really need a matrix? \n", 242 | "Of course, we can use sparse matrices to save space in memory. But do we really need any kind of matrix? \n", 243 | "The same algorithm can be written considering just the three values $aa,bb,cc$. \n", 244 | "\n", 245 | "**In the following algorithm, even if the gain in speed is not so much, we save a lot of space in memory!!** " 246 | ] 247 | }, 248 | { 249 | "cell_type": "code", 250 | "execution_count": 7, 251 | "metadata": {}, 252 | "outputs": [], 253 | "source": [ 254 | "def SOR4(aa, bb, cc, b, w=1, eps=1e-10, N_max = 100):\n", 255 | " N = len(b)\n", 256 | " x0 = np.ones_like(b, dtype=np.float64) # initial guess\n", 257 | " x_new = np.ones_like(x0) # new solution\n", 258 | " for k in range(1,N_max+1):\n", 259 | " for i in range(N):\n", 260 | " if (i==0):\n", 261 | " S = cc * x_new[1]\n", 262 | " elif (i==N-1):\n", 263 | " S = aa * x_new[N-2]\n", 264 | " else:\n", 265 | " S = aa * x_new[i-1] + cc * x_new[i+1]\n", 266 | " x_new[i] = (1-w)*x_new[i] + (w/bb) * (b[i] - S) \n", 267 | " if norm(x_new - x0) < eps:\n", 268 | " return x_new\n", 269 | " x0 = x_new.copy()\n", 270 | " if k==N_max:\n", 271 | " print(\"Fail to converge in {} iterations\".format(k))\n", 272 | " return x_new" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 8, 278 | "metadata": {}, 279 | "outputs": [ 280 | { 281 | "name": "stdout", 282 | "output_type": "stream", 283 | "text": [ 284 | "430 ms ± 4.06 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)\n" 285 | ] 286 | } 287 | ], 288 | "source": [ 289 | "%%timeit\n", 290 | "SOR4(aa,bb,cc,b)" 291 | ] 292 | }, 293 | { 294 | "cell_type": "markdown", 295 | "metadata": {}, 296 | "source": [ 297 | "\n", 298 | "## Cython\n", 299 | "\n", 300 | "\n", 301 | "For those who are not familiar with Cython, I suggest to read this introduction [link](https://cython.readthedocs.io/en/latest/src/userguide/numpy_tutorial.html).\n", 302 | "\n", 303 | "Cython, basically, consists in adding types to the python variables. \n", 304 | "\n", 305 | "Let's see what happens to the speed when we add types to the previous pure python function (SOR4)" 306 | ] 307 | }, 308 | { 309 | "cell_type": "code", 310 | "execution_count": 9, 311 | "metadata": {}, 312 | "outputs": [], 313 | "source": [ 314 | "%%cython\n", 315 | "import numpy as np\n", 316 | "from scipy.linalg import norm\n", 317 | "cimport numpy as np \n", 318 | "cimport cython\n", 319 | "\n", 320 | "@cython.boundscheck(False) # turn off bounds-checking for entire function\n", 321 | "@cython.wraparound(False) # turn off negative index wrapping for entire function\n", 322 | "def SOR_cy(np.float64_t aa, \n", 323 | " np.float64_t bb, np.float64_t cc, \n", 324 | " np.ndarray[np.float64_t , ndim=1] b, \n", 325 | " double w=1, double eps=1e-10, int N_max = 100):\n", 326 | " \n", 327 | " cdef unsigned int N = b.size\n", 328 | " cdef np.ndarray[np.float64_t , ndim=1] x0 = np.ones(N, dtype=np.float64) # initial guess\n", 329 | " cdef np.ndarray[np.float64_t , ndim=1] x_new = np.ones(N, dtype=np.float64) # new solution\n", 330 | " cdef unsigned int i, k\n", 331 | " cdef np.float64_t S\n", 332 | " \n", 333 | " for k in range(1,N_max+1):\n", 334 | " for i in range(N):\n", 335 | " if (i==0):\n", 336 | " S = cc * x_new[1]\n", 337 | " elif (i==N-1):\n", 338 | " S = aa * x_new[N-2]\n", 339 | " else:\n", 340 | " S = aa * x_new[i-1] + cc * x_new[i+1]\n", 341 | " x_new[i] = (1-w)*x_new[i] + (w/bb) * (b[i] - S) \n", 342 | " if norm(x_new - x0) < eps:\n", 343 | " return x_new\n", 344 | " x0 = x_new.copy()\n", 345 | " if k==N_max:\n", 346 | " print(\"Fail to converge in {} iterations\".format(k))\n", 347 | " return x_new" 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": 10, 353 | "metadata": {}, 354 | "outputs": [ 355 | { 356 | "name": "stdout", 357 | "output_type": "stream", 358 | "text": [ 359 | "1.98 ms ± 11.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)\n" 360 | ] 361 | } 362 | ], 363 | "source": [ 364 | "%%timeit\n", 365 | "SOR_cy(aa,bb,cc,b)" 366 | ] 367 | }, 368 | { 369 | "cell_type": "markdown", 370 | "metadata": {}, 371 | "source": [ 372 | "### About 100 times faster!!!\n", 373 | "\n", 374 | "That's good.\n", 375 | "\n", 376 | "So... those who are not familiar with Cython maybe are confused about the new type `np.float64_t`. We wrote: \n", 377 | "```python\n", 378 | "import numpy as np\n", 379 | "cimport numpy as np \n", 380 | "``` \n", 381 | "The first line imports numpy module in the python space. \n", 382 | "It only gives access to Numpy’s pure-Python API and it occurs at runtime.\n", 383 | "\n", 384 | "The second line gives access to the Numpy’s C API defined in the `__init__.pxd` file during compile time.\n", 385 | "\n", 386 | "Even if they are both named `np`, they are automatically recognized.\n", 387 | "In `__init__.pdx` it is defined:\n", 388 | "```\n", 389 | "ctypedef double npy_float64\n", 390 | "ctypedef npy_float64 float64_t\n", 391 | "``` \n", 392 | "The `np.float64_t` represents the type `double` in C." 393 | ] 394 | }, 395 | { 396 | "cell_type": "markdown", 397 | "metadata": {}, 398 | "source": [ 399 | "### Memoryviews\n", 400 | "\n", 401 | "Let us re-write the previous code using the faster [memoryviews](https://cython.readthedocs.io/en/latest/src/userguide/memoryviews.html). \n", 402 | "I suggest to the reader to have a fast look at the memoryviews manual in the link. There are no difficult concepts and the notation is not so different from the notation used in the previous function. \n", 403 | "\n", 404 | "Memoryviews is another tool to help speed up the algorithm.\n", 405 | "\n", 406 | "I have to admit that when I was writing the new code I realized that using the function `norm` is not the optimal way. (I got an error because `norm` only accepts ndarrays... so, thanks memoryviews :) ). \n", 407 | "Well, the `norm` function computes a square root, which still requires some computations. \n", 408 | "We can define our own function `distance2` (which is the square of the distance) that is compared with the square of the tolerance parameter `eps * eps`. This is another improvement of the algorithm." 409 | ] 410 | }, 411 | { 412 | "cell_type": "code", 413 | "execution_count": 11, 414 | "metadata": {}, 415 | "outputs": [], 416 | "source": [ 417 | "%%cython\n", 418 | "import numpy as np\n", 419 | "cimport numpy as np\n", 420 | "cimport cython\n", 421 | "\n", 422 | "cdef double distance2(double[:] a, double[:] b, unsigned int N):\n", 423 | " cdef double dist = 0\n", 424 | " cdef unsigned int i \n", 425 | " for i in range(N):\n", 426 | " dist += (a[i] - b[i]) * (a[i] - b[i])\n", 427 | " return dist\n", 428 | "\n", 429 | "@cython.boundscheck(False)\n", 430 | "@cython.wraparound(False)\n", 431 | "def SOR_cy2(double aa, \n", 432 | " double bb, double cc, \n", 433 | " double[:] b, \n", 434 | " double w=1, double eps=1e-10, int N_max = 200):\n", 435 | " \n", 436 | " cdef unsigned int N = b.size \n", 437 | " cdef double[:] x0 = np.ones(N, dtype=np.float64) # initial guess\n", 438 | " cdef double[:] x_new = np.ones(N, dtype=np.float64) # new solution\n", 439 | " cdef unsigned int i, k\n", 440 | " cdef double S\n", 441 | " \n", 442 | " for k in range(1,N_max+1):\n", 443 | " for i in range(N):\n", 444 | " if (i==0):\n", 445 | " S = cc * x_new[1]\n", 446 | " elif (i==N-1):\n", 447 | " S = aa * x_new[N-2]\n", 448 | " else:\n", 449 | " S = aa * x_new[i-1] + cc * x_new[i+1]\n", 450 | " x_new[i] = (1-w)*x_new[i] + (w/bb) * (b[i] - S) \n", 451 | " if distance2(x_new, x0, N) < eps*eps:\n", 452 | " return np.asarray(x_new)\n", 453 | " x0[:] = x_new\n", 454 | " if k==N_max:\n", 455 | " print(\"Fail to converge in {} iterations\".format(k))\n", 456 | " return np.asarray(x_new)" 457 | ] 458 | }, 459 | { 460 | "cell_type": "code", 461 | "execution_count": 12, 462 | "metadata": {}, 463 | "outputs": [ 464 | { 465 | "name": "stdout", 466 | "output_type": "stream", 467 | "text": [ 468 | "1.17 ms ± 18.8 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" 469 | ] 470 | } 471 | ], 472 | "source": [ 473 | "%%timeit\n", 474 | "SOR_cy2(aa,bb,cc,b)" 475 | ] 476 | }, 477 | { 478 | "cell_type": "markdown", 479 | "metadata": {}, 480 | "source": [ 481 | "### Good job!! Another improvement!" 482 | ] 483 | }, 484 | { 485 | "cell_type": "markdown", 486 | "metadata": {}, 487 | "source": [ 488 | "\n", 489 | "## C code\n", 490 | "\n", 491 | "The last improvement is to write the function in C code and call it from python. \n", 492 | "Inside the folder `functions/C` you can find the header file `SOR.h` and the implementation file `SOR.c` (you will find also the `mainSOR.c` if you want to test the SOR algorithm directly in C). \n", 493 | "I will call the function `SOR_abc` declared in the header `SOR.h`. \n", 494 | "First it is declared as extern, and then it is called inside `SOR_c` with a cast to ``.\n", 495 | "\n", 496 | "If you are using docker the next function will compile correctly. If you are not using docker you have to replace the INCLUDE_PATH with the output of the next cell:" 497 | ] 498 | }, 499 | { 500 | "cell_type": "code", 501 | "execution_count": 13, 502 | "metadata": {}, 503 | "outputs": [ 504 | { 505 | "name": "stdout", 506 | "output_type": "stream", 507 | "text": [ 508 | "INCLUDE_PATH = /home/jovyan/work/functions/C\n" 509 | ] 510 | } 511 | ], 512 | "source": [ 513 | "print(\"INCLUDE_PATH = \", os.getcwd() + \"/functions/C\")" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": 14, 519 | "metadata": {}, 520 | "outputs": [], 521 | "source": [ 522 | "%%cython -I /home/jovyan/work/functions/C\n", 523 | "# With docker no need to modify anything.\n", 524 | "#\n", 525 | "# If you are not using docker, just replace the line above, \n", 526 | "# with the line below and replace INCLUDE_PATH:\n", 527 | "# \n", 528 | "# %%cython -I INCLUDE_PATH\n", 529 | "#\n", 530 | "# The %%cython directive must be the first keyword in the cell\n", 531 | "\n", 532 | "cdef extern from \"SOR.c\":\n", 533 | " pass\n", 534 | "cdef extern from \"SOR.h\":\n", 535 | " double* SOR_abc(double, double, double, double *, int, double, double, int)\n", 536 | "\n", 537 | "import numpy as np\n", 538 | "cimport cython\n", 539 | "\n", 540 | "@cython.boundscheck(False)\n", 541 | "@cython.wraparound(False)\n", 542 | "def SOR_c(double aa, double bb, double cc, B, double w=1, double eps=1e-10, int N_max = 200): \n", 543 | "\n", 544 | " if not B.flags['C_CONTIGUOUS']:\n", 545 | " B = np.ascontiguousarray(B) # Makes a contiguous copy of the numpy array\n", 546 | " \n", 547 | " cdef double[::1] arr_memview = B \n", 548 | " cdef double[::1] x = SOR_abc(aa, bb, cc, \n", 549 | " &arr_memview[0], arr_memview.shape[0], \n", 550 | " w, eps, N_max)\n", 551 | " return np.asarray(x)" 552 | ] 553 | }, 554 | { 555 | "cell_type": "code", 556 | "execution_count": 15, 557 | "metadata": {}, 558 | "outputs": [ 559 | { 560 | "name": "stdout", 561 | "output_type": "stream", 562 | "text": [ 563 | "1.21 ms ± 15.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)\n" 564 | ] 565 | } 566 | ], 567 | "source": [ 568 | "%%timeit\n", 569 | "SOR_c(aa,bb,cc,b)" 570 | ] 571 | }, 572 | { 573 | "cell_type": "markdown", 574 | "metadata": {}, 575 | "source": [ 576 | "## Well... it looks like that using Cython with memoryviews has the same performances as wrapping a C function.\n", 577 | "\n", 578 | "For this reason, I used the cython version as solver in the class `BS_pricer`. \n", 579 | "We already compared some performances in the notebook **1.2 - BS PDE**, and we saw that the SOR algorithm is slow compared to the LU or Thomas algorithms. \n", 580 | "Just for curiosity, let us compare the speed of the python PDE_price method implemented with cython SOR algorithm, and a pricer with same SOR algorithm fully implemented in C." 581 | ] 582 | }, 583 | { 584 | "cell_type": "code", 585 | "execution_count": 16, 586 | "metadata": {}, 587 | "outputs": [], 588 | "source": [ 589 | "from functions.Parameters import Option_param\n", 590 | "from functions.Processes import Diffusion_process\n", 591 | "from functions.BS_pricer import BS_pricer\n", 592 | "\n", 593 | "opt_param = Option_param(S0=100, K=100, T=1, exercise=\"European\", payoff=\"call\" )\n", 594 | "diff_param = Diffusion_process(r=0.1, sig=0.2)\n", 595 | "BS = BS_pricer(opt_param, diff_param)" 596 | ] 597 | }, 598 | { 599 | "cell_type": "markdown", 600 | "metadata": {}, 601 | "source": [ 602 | "\n", 603 | "## BS python vs C" 604 | ] 605 | }, 606 | { 607 | "cell_type": "markdown", 608 | "metadata": {}, 609 | "source": [ 610 | "Run the command `make` to compile the C [code](./functions/C/PDE_solver.c):" 611 | ] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "execution_count": 17, 616 | "metadata": {}, 617 | "outputs": [ 618 | { 619 | "data": { 620 | "text/plain": [ 621 | "0" 622 | ] 623 | }, 624 | "execution_count": 17, 625 | "metadata": {}, 626 | "output_type": "execute_result" 627 | } 628 | ], 629 | "source": [ 630 | "os.system(\"cd ./functions/C/ && make\")" 631 | ] 632 | }, 633 | { 634 | "cell_type": "markdown", 635 | "metadata": {}, 636 | "source": [ 637 | "Python program with Cython SOR method:" 638 | ] 639 | }, 640 | { 641 | "cell_type": "code", 642 | "execution_count": 18, 643 | "metadata": {}, 644 | "outputs": [ 645 | { 646 | "name": "stdout", 647 | "output_type": "stream", 648 | "text": [ 649 | "Price: 13.269170 Time: 7.882848\n" 650 | ] 651 | } 652 | ], 653 | "source": [ 654 | "print(\"Price: {0:.6f} Time: {1:.6f}\".format(*BS.PDE_price((3000,2000), Time=True, solver=\"SOR\")))" 655 | ] 656 | }, 657 | { 658 | "cell_type": "markdown", 659 | "metadata": {}, 660 | "source": [ 661 | "Pure C program:" 662 | ] 663 | }, 664 | { 665 | "cell_type": "code", 666 | "execution_count": 19, 667 | "metadata": {}, 668 | "outputs": [ 669 | { 670 | "name": "stdout", 671 | "output_type": "stream", 672 | "text": [ 673 | "The price is: 13.269139 \n", 674 | " \n", 675 | "CPU times: user 0 ns, sys: 12 ms, total: 12 ms\n", 676 | "Wall time: 16.5 s\n" 677 | ] 678 | } 679 | ], 680 | "source": [ 681 | "%%time\n", 682 | "result = subprocess.run(\"./functions/C/BS_sor\", stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n", 683 | "print(result.stdout.decode('utf-8'))" 684 | ] 685 | }, 686 | { 687 | "cell_type": "markdown", 688 | "metadata": {}, 689 | "source": [ 690 | "The C code is slower. \n", 691 | "### Exercise:\n", 692 | "Can you guess why the C code is slower? If you know, send me an email " 693 | ] 694 | } 695 | ], 696 | "metadata": { 697 | "kernelspec": { 698 | "display_name": "Python 3", 699 | "language": "python", 700 | "name": "python3" 701 | }, 702 | "language_info": { 703 | "codemirror_mode": { 704 | "name": "ipython", 705 | "version": 3 706 | }, 707 | "file_extension": ".py", 708 | "mimetype": "text/x-python", 709 | "name": "python", 710 | "nbconvert_exporter": "python", 711 | "pygments_lexer": "ipython3", 712 | "version": "3.7.3" 713 | } 714 | }, 715 | "nbformat": 4, 716 | "nbformat_minor": 2 717 | } 718 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published 637 | by the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . 662 | -------------------------------------------------------------------------------- /2.3 American Options.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# American options\n", 8 | "\n", 9 | "\n", 10 | "## Contents\n", 11 | " - [Binomial tree](#sec1)\n", 12 | " - [Longstaff - Schwartz](#sec2)\n", 13 | " \n", 14 | " \n", 15 | "The American option problem is an optimal stopping problem formulated as follows:\n", 16 | "\n", 17 | "$$ V(t,s) = \\sup_{\\tau \\in [t,T]} \\mathbb{E}^{\\mathbb{Q}}\\biggl[ e^{-r(T-\\tau)} \\Phi(S_{\\tau}) \\bigg| S_t=s \\biggr]$$\n", 18 | "\n", 19 | "where $\\Phi(\\cdot)$ is the payoff, also called *intrinsic value*. \n", 20 | "This formula resembles the formula of a European option, except that in this case the option can be exercised at any time. But... at which time? The problem is to find the best exercise time $\\tau$ that maximizes the expectation.\n", 21 | "\n", 22 | "Notice that the time $\\tau$ is a random variable! It can be different for different paths of the stock process. \n", 23 | "The solution of the problem provides a strategy, that at each time assesses if it is optimal to exercise the option or not, depending on the current value of the underlying stock.\n", 24 | "\n", 25 | "This notebook is dedicated only to the pricing problem, i.e. just to find $V(t,s)$, and not to find $\\tau$.\n", 26 | "\n", 27 | "It can be proved that the function $V(t,s)$ is the (weak) solution of the following PDE:\n", 28 | "\n", 29 | "\\begin{equation}\n", 30 | "\\max \\biggl\\{ \\frac{\\partial V(t,s)}{\\partial t} \n", 31 | " + r\\,s \\frac{\\partial V(t,s)}{\\partial s}\n", 32 | " + \\frac{1}{2} \\sigma^2 s^2 \\frac{\\partial^2 V(t,s)}{\\partial s^2} - r V(t,s), \\; \n", 33 | " \\Phi(s) - V(t,s) \\biggr\\} = 0.\n", 34 | "\\end{equation}\n", 35 | "\n", 36 | "$$ V(T,s) = \\Phi(s) $$\n", 37 | "\n", 38 | "The numerical algorithm for solving this PDE is almost identical to the algorithm proposed in the notebook **2.1** for the Black-Scholes PDE. \n", 39 | "\n", 40 | "Let us have a look at the differences between the implementation of the European and the American algorithm, in the class `BS_pricer`:\n", 41 | "\n", 42 | "```python\n", 43 | "if self.exercise==\"European\": \n", 44 | " for i in range(Ntime-2,-1,-1):\n", 45 | " offset[0] = a * V[0,i] \n", 46 | " offset[-1] = c * V[-1,i]\n", 47 | " V[1:-1,i] = spsolve( D, (V[1:-1,i+1] - offset) )\n", 48 | "elif self.exercise==\"American\":\n", 49 | " for i in range(Ntime-2,-1,-1):\n", 50 | " offset[0] = a * V[0,i]\n", 51 | " offset[-1] = c * V[-1,i]\n", 52 | " V[1:-1,i] = np.maximum( spsolve( D, (V[1:-1,i+1] - offset) ), Payoff[1:-1])\n", 53 | "```\n", 54 | "\n", 55 | "The European and the American algorithms just differ in one line!! \n", 56 | "\n", 57 | "I don't consider dividends in the notebook. In absence of dividends the American call has the same value of the European call. For this reason, I'm going to consider only the pricing problem of a put option\n", 58 | "\n", 59 | "$$ \\Phi(S_{\\tau}) = ( K - S_{\\tau} )^+ $$\n" 60 | ] 61 | }, 62 | { 63 | "cell_type": "code", 64 | "execution_count": 1, 65 | "metadata": {}, 66 | "outputs": [], 67 | "source": [ 68 | "from functions.BS_pricer import BS_pricer\n", 69 | "from functions.Parameters import Option_param\n", 70 | "from functions.Processes import Diffusion_process\n", 71 | "\n", 72 | "import numpy as np\n", 73 | "import scipy.stats as ss\n", 74 | "\n", 75 | "import matplotlib.pyplot as plt\n", 76 | "%matplotlib inline\n", 77 | "from IPython.display import display\n", 78 | "import sympy; sympy.init_printing()\n", 79 | "\n", 80 | "def display_matrix(m):\n", 81 | " display(sympy.Matrix(m))" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 5, 87 | "metadata": {}, 88 | "outputs": [], 89 | "source": [ 90 | "# Creates the object with the parameters of the option\n", 91 | "opt_param = Option_param(S0=100, K=100, T=1, exercise=\"American\", payoff=\"put\" )\n", 92 | "# Creates the object with the parameters of the process\n", 93 | "diff_param = Diffusion_process(r=0.1, sig=0.2)\n", 94 | "# Creates the pricer object\n", 95 | "BS = BS_pricer(opt_param, diff_param)" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": {}, 101 | "source": [ 102 | "The class `BS_pricer` implements two algorithms to price American options:\n", 103 | "- the Longstaff-Schwartz Method (see section [below](#sec2))\n", 104 | "- the PDE method" 105 | ] 106 | }, 107 | { 108 | "cell_type": "code", 109 | "execution_count": 24, 110 | "metadata": {}, 111 | "outputs": [ 112 | { 113 | "data": { 114 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAK0AAAASCAYAAAApM17jAAAABHNCSVQICAgIfAhkiAAABrFJREFUaIHt2mmsXVUVB/Bf66vSagEBLVEJIJhQ2gRErSjBDgwKWFIw+IHIEAYnIsWpTBpunBAkKIgDDTgQookDlVAGQVIsFAiioFRQwfYpBJpKtVBLaW37/LD28Z537jnn3nPf6xdz/8nN6Vtr7el/1ll77bXLAAP8n+EUjKTfWX20Pw534hlswir8FO8qsb0Md+PpZPtPPIJLsPs4zXf3JF+Cp9I4L+A+nImJJW2Gc30Wf2sq5jEBZ+BBbMBLaS3n4hUl9qfXjJH9tlWM1YRjeBO+h2exOa3vG3hthX2Gw/FzPJfaPZfGPbZg1w/HjdYyoaaDvfCYIPk1OBvXdVlYHpdhEdbhF3ge++N4DOFU3Jiz34Lf4XGsxatxKN4uCD5UOPRY5vtRfEcQvgx/xzSciF3ESzlJOEmGYewqXmwR/8YVJfIbxAe0FrdgI47EgRVjHIwFFes6HPNwK95f0DXleD/cj9fjZvwJszAXf8Zhqa8iPocvpv6XCv72wFsFj4tytv1w3M9aOjABv8Jf8TXNI+2eIjKsEQTlMTf1t6og36miry8n+2+Pw3znYb7Or31PQe4IPlDQDadfr1igvb49cvJJIvqMiMjaKx5IbY4vyPvh+JdJ/omC/Mok/27J+JmD3YWpJfpJhb/74biftXRgIbbjPWhp7rTvTG1urtC/KLbNXnCQNmlVGOt84aLU7psF+bBmTntD6uecEt3MpPttj31l9s/oTCuacvzmZL9ap0NNFbvGRrHDZZgonGUjXtfjnOtQxXGjtZTl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qvoW7rMrSnH9He5cGPSfakgPyqNsV5n+a4JxzRcy5Cx4W7xAvc1+mv7mairHSmS7yVpQtPFVeQEsaVk+eD7xFazXNxqrRMHsdniBa8R17JjxWnaFYd7xQGhiGH8IP37pDTPZaIov0F8qMeJiHib8mvcuwTJK1ObGeKOfrPYcuui84fTc3GXtTTlmCjD3Y+rRRrwhCjszxUHxItLxvlUsrlY1EwfEu/8BMHj2cJxMzTluN+11KKlOnINJ90+JbpJIqd5UBxEtooa3FKdJ+eZ+JbYSp5Pti+IXKql2am+br6Zru53T85+Nn4s7ujXiy39H8IpT1X9fzc+K2691gtHXS2i2D5d5j5d9wNYHk04zrAXvi/+b8AW/E3k0HUc7yai8erUZp24vSqrNbc043gsaxlggAEGGGCAAQaA/wIaTbIUKTW09QAAAABJRU5ErkJggg==\n", 115 | "text/latex": [ 116 | "$\\displaystyle 4.834259780628$" 117 | ], 118 | "text/plain": [ 119 | "4.834259780628" 120 | ] 121 | }, 122 | "execution_count": 24, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "BS.LSM(N=10000, paths=10000, order=2) # Longstaff Schwartz Method" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 4, 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "data": { 138 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAANMAAAASCAYAAADBs+vIAAAABHNCSVQICAgIfAhkiAAABlhJREFUaIHtmmuIVVUUx3/aWI6ViFkORampUDlgGVkGOqeyyMrSzD5ImkQZFGX2ECvB2wvTpJIehBRkSFGZGkmaJpUliT0sGXpZzgWlhmmmfL91+rDW4Z7Zs/d57HvvDMT9w+HM7LXW3nv919mvtS9UUEEFHYLJQKs+d3rYXw+sAXYAB4BtwPvACIvuLcBLwJfAbm1zSUL9+Uj/zKcxwXYk8AHwF3BI32uA6wy9ecA6YLv68A+wGZgDnOaouwtwB7AR2APsV5v7gRMs+lNj/AifYxY7H86iSB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XqLrAp4CEmtHkASLquBiylkgS6MqfsC1dlOujsWiOes1PEFN8e+Nmk560xfUsWlF/EXU9HHlqM3EY70+xzyZSqf4JAHFDeYeqr9QaP8Zi3/xmEXplZnpWxns+r3SVJUVCMfyn7ap+CjWKj15lLWC/GclTq+4Oa41DYmZ53pS2xcwmzeISQzYcMw5DLzK2RGSJPxCmcM12E+LD+coi4fhNs0Mzu0HtkeDAZOtLRfq+98ynbO1HfaTNBk5N5qMXDEodNd9Y7jjklWlDq+4Oa41DYmZ53lS0niksO9dA5Ebt3NWfZWCvvfswzZGO3QAdw/xwlIXpmG0PawGqIfso1rBR6zyJeo7Gmj/Grt105k9gPxrYb26Erh0naDRd7TUnYJkozZg3t7C4WfxXwUo2NDgN9qnsMdXx+OfeNSDGchcpTWlygS4xL3c6I0WKedGUDb2Xwpcis9GvgZOdg1IvcCNyC31rNou0cdpw8UPuARwJv6dzOSng4xUev4DGhACB+I3B11Rw60Cyx9fhC5VH4cufPapD6MR1aYuyjcZVyLbP3WIzfsLUgCog4JbqPqm1iLTBb12q8hyG/+DiFbzbgZcJq+F8XohMjKWVb4cOwbl2I4K5cvUWSJixM53KM9r7L+Flk35K5pI3KYPIrcOa3EnskK23E9eUO/DngH+AX5+I8AfyNBmYIMWBd6I1nGBmSr14L8WsO8+6kFXkEOxc3qwy7kzJXDPtMBPILc2O9EPoYGJAXbP6ZPIJNNlsRDjmycxdVhi68Px75x8eWsnL6EyBqXCiqooIIKKqigggr+P/gPgsQIrNiAnyYAAAAASUVORK5CYII=\n", 139 | "text/latex": [ 140 | "$\\displaystyle 4.815639714559457$" 141 | ], 142 | "text/plain": [ 143 | "4.815639714559457" 144 | ] 145 | }, 146 | "execution_count": 4, 147 | "metadata": {}, 148 | "output_type": "execute_result" 149 | } 150 | ], 151 | "source": [ 152 | "BS.PDE_price((7000,5000))" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": 10, 158 | "metadata": {}, 159 | "outputs": [ 160 | { 161 |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5TC0IkD5jZn4A+zrnLws4iklfUghDJBfPPJc88wmcT/CMeRQoNdVKL5E5J4D9mVgb/kJtV+NNNIoWGTjGJiEiWdIpJRESypAIhIiJZUoEQEZEsqUCIiEiWVCBERCRLKhAiIpIlFQgREcnS/wfT5idyp1X72gAAAABJRU5ErkJggg==\n", 163 | "text/plain": [ 164 | "
" 165 | ] 166 | }, 167 | "metadata": { 168 | "needs_background": "light" 169 | }, 170 | "output_type": "display_data" 171 | } 172 | ], 173 | "source": [ 174 | "BS.plot([60,140,0,50])" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "metadata": {}, 180 | "source": [ 181 | "\n", 182 | "## Binomial tree\n", 183 | "\n", 184 | "One of the most used methods for pricing American options is the Binomial tree. \n", 185 | "\n", 186 | "We have already encountered the binomial tree in the notebook **1.1**. The following algorithm is almost a copy/paste from that notebook. \n", 187 | "There are just two additional lines:\n", 188 | "- `S_T = S_T * u`. This an efficient method to retrive the price vector at each time steps. \n", 189 | "- `V = np.maximum( V, K-S_T )`. This line computes the maximum between the conditional expectation V and the intrisic value. " 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": 2, 195 | "metadata": {}, 196 | "outputs": [], 197 | "source": [ 198 | "S0=100.0 # spot stock price\n", 199 | "K=100.0 # strike\n", 200 | "T=1.0 # maturity \n", 201 | "r=0.1 # risk free rate \n", 202 | "sig=0.2 # diffusion coefficient or volatility" 203 | ] 204 | }, 205 | { 206 | "cell_type": "code", 207 | "execution_count": 15, 208 | "metadata": {}, 209 | "outputs": [ 210 | { 211 | "name": "stdout", 212 | "output_type": "stream", 213 | "text": [ 214 | "American BS Tree Price: 4.81624866310944\n" 215 | ] 216 | } 217 | ], 218 | "source": [ 219 | "N = 25000 # number of periods or number of time steps \n", 220 | "payoff = \"put\" # payoff \n", 221 | "\n", 222 | "dT = float(T) / N # Delta t\n", 223 | "u = np.exp(sig * np.sqrt(dT)) # up factor\n", 224 | "d = 1.0 / u # down factor \n", 225 | "\n", 226 | "V = np.zeros(N+1) # initialize the price vector\n", 227 | "S_T = np.array( [(S0 * u**j * d**(N - j)) for j in range(N + 1)] ) # price S_T at time T\n", 228 | "\n", 229 | "a = np.exp(r * dT) # risk free compound return\n", 230 | "p = (a - d)/ (u - d) # risk neutral up probability\n", 231 | "q = 1.0 - p # risk neutral down probability \n", 232 | "\n", 233 | "if payoff ==\"call\":\n", 234 | " V[:] = np.maximum(S_T-K, 0.0)\n", 235 | "elif payoff ==\"put\":\n", 236 | " V[:] = np.maximum(K-S_T, 0.0)\n", 237 | "\n", 238 | "for i in range(N-1, -1, -1):\n", 239 | " V[:-1] = np.exp(-r*dT) * (p * V[1:] + q * V[:-1]) # the price vector is overwritten at each step\n", 240 | " S_T = S_T * u # it is a tricky way to obtain the price at the previous time step\n", 241 | " if payoff==\"call\":\n", 242 | " V = np.maximum( V, S_T-K )\n", 243 | " elif payoff==\"put\":\n", 244 | " V = np.maximum( V, K-S_T )\n", 245 | " \n", 246 | "print(\"American BS Tree Price: \", V[0])" 247 | ] 248 | }, 249 | { 250 | "cell_type": "markdown", 251 | "metadata": {}, 252 | "source": [ 253 | "\n", 254 | "## Longstaff - Schwartz Method\n", 255 | "\n", 256 | "This is a Monte Carlo algorithm proposed by Longstaff and Schwartz in the paper [1]:\n", 257 | "[LS Method](https://people.math.ethz.ch/~hjfurrer/teaching/LongstaffSchwartzAmericanOptionsLeastSquareMonteCarlo.pdf)\n", 258 | "\n", 259 | "The algorithm is not difficult to implement, but it can be difficult to understand. I think this is the reason the authors started the paper with an example. \n", 260 | "Well. I think they had a good idea, and for this reason I want to reproduce their example here. \n", 261 | "\n", 262 | "The same code is copied in the class `BS_pricer` where the function `LSM` is implemented.\n", 263 | "\n", 264 | "**If in the following code you feel that something is unclear, I suggest you to follow the steps (not in python) proposed in the original paper**." 265 | ] 266 | }, 267 | { 268 | "cell_type": "code", 269 | "execution_count": 6, 270 | "metadata": {}, 271 | "outputs": [], 272 | "source": [ 273 | "N = 4 # number of time steps\n", 274 | "r = 0.06 # interest rate\n", 275 | "K = 1.1 # strike \n", 276 | "T = 3 # Maturity\n", 277 | "\n", 278 | "dt = T/(N-1) # time interval\n", 279 | "df = np.exp(-r * dt) # discount factor per time interval" 280 | ] 281 | }, 282 | { 283 | "cell_type": "code", 284 | "execution_count": 9, 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "S = np.array([\n", 289 | " [1.00, 1.09, 1.08, 1.34],\n", 290 | " [1.00, 1.16, 1.26, 1.54],\n", 291 | " [1.00, 1.22, 1.07, 1.03],\n", 292 | " [1.00, 0.93, 0.97, 0.92],\n", 293 | " [1.00, 1.11, 1.56, 1.52],\n", 294 | " [1.00, 0.76, 0.77, 0.90],\n", 295 | " [1.00, 0.92, 0.84, 1.01],\n", 296 | " [1.00, 0.88, 1.22, 1.34]])" 297 | ] 298 | }, 299 | { 300 | "cell_type": "code", 301 | "execution_count": 10, 302 | "metadata": {}, 303 | "outputs": [ 304 | { 305 | "data": { 306 | "text/latex": [ 307 | "$\\displaystyle \\left[\\begin{matrix}1.0 & 1.09 & 1.08 & 1.34\\\\1.0 & 1.16 & 1.26 & 1.54\\\\1.0 & 1.22 & 1.07 & 1.03\\\\1.0 & 0.93 & 0.97 & 0.92\\\\1.0 & 1.11 & 1.56 & 1.52\\\\1.0 & 0.76 & 0.77 & 0.9\\\\1.0 & 0.92 & 0.84 & 1.01\\\\1.0 & 0.88 & 1.22 & 1.34\\end{matrix}\\right]$" 308 | ], 309 | "text/plain": [ 310 | "⎡1.0 1.09 1.08 1.34⎤\n", 311 | "⎢ ⎥\n", 312 | "⎢1.0 1.16 1.26 1.54⎥\n", 313 | "⎢ ⎥\n", 314 | "⎢1.0 1.22 1.07 1.03⎥\n", 315 | "⎢ ⎥\n", 316 | "⎢1.0 0.93 0.97 0.92⎥\n", 317 | "⎢ ⎥\n", 318 | "⎢1.0 1.11 1.56 1.52⎥\n", 319 | "⎢ ⎥\n", 320 | "⎢1.0 0.76 0.77 0.9 ⎥\n", 321 | "⎢ ⎥\n", 322 | "⎢1.0 0.92 0.84 1.01⎥\n", 323 | "⎢ ⎥\n", 324 | "⎣1.0 0.88 1.22 1.34⎦" 325 | ] 326 | }, 327 | "metadata": {}, 328 | "output_type": "display_data" 329 | } 330 | ], 331 | "source": [ 332 | "display_matrix(S)" 333 | ] 334 | }, 335 | { 336 | "cell_type": "markdown", 337 | "metadata": {}, 338 | "source": [ 339 | "In the previous cell we defined the stock matrix S. \n", 340 | "It has 8 rows that correspond to the number of paths. \n", 341 | "The 4 columns correspond to the 4 time steps, i.e. each row is a path with 4 time steps." 342 | ] 343 | }, 344 | { 345 | "cell_type": "code", 346 | "execution_count": 13, 347 | "metadata": {}, 348 | "outputs": [ 349 | { 350 | "name": "stdout", 351 | "output_type": "stream", 352 | "text": [ 353 | "Example price= 0.11443433004505696\n" 354 | ] 355 | } 356 | ], 357 | "source": [ 358 | "H = np.maximum(K - S, 0) # intrinsic values for put option\n", 359 | "V = np.zeros_like(H) # value matrix\n", 360 | "V[:,-1] = H[:,-1]\n", 361 | "\n", 362 | "# Valuation by LS Method\n", 363 | "for t in range(N-2, 0, -1):\n", 364 | "\n", 365 | " good_paths = H[:,t] > 0 # paths where the intrinsic value is positive \n", 366 | " # the regression is performed only on these paths \n", 367 | " \n", 368 | " rg = np.polyfit( S[good_paths, t], V[good_paths, t+1] * df, 2) # polynomial regression\n", 369 | " C = np.polyval( rg, S[good_paths,t] ) # evaluation of regression \n", 370 | " \n", 371 | " exercise = np.zeros( len(good_paths), dtype=bool) # initialize\n", 372 | " exercise[good_paths] = H[good_paths,t] > C # paths where it is optimal to exercise\n", 373 | " \n", 374 | " V[exercise,t] = H[exercise,t] # set V equal to H where it is optimal to exercise \n", 375 | " V[exercise,t+1:] = 0 # set future cash flows, for that path, equal to zero \n", 376 | " discount_path = (V[:,t] == 0) # paths where we didn't exercise \n", 377 | " V[discount_path,t] = V[discount_path,t+1] * df # set V[t] in continuation region\n", 378 | " \n", 379 | "V0 = np.mean(V[:,1]) * df # discounted expectation of V[t=1]\n", 380 | "print(\"Example price= \", V0)" 381 | ] 382 | }, 383 | { 384 | "cell_type": "markdown", 385 | "metadata": {}, 386 | "source": [ 387 | "The matrix `H = np.maximum(K - S, 0)`, is the matrix of intrinsic values:" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": 15, 393 | "metadata": {}, 394 | "outputs": [ 395 | { 396 | "data": { 397 | "text/latex": [ 398 | "$\\displaystyle \\left[\\begin{matrix}0.1 & 0.01 & 0.02 & 0.0\\\\0.1 & 0.0 & 0.0 & 0.0\\\\0.1 & 0.0 & 0.03 & 0.07\\\\0.1 & 0.17 & 0.13 & 0.18\\\\0.1 & 0.0 & 0.0 & 0.0\\\\0.1 & 0.34 & 0.33 & 0.2\\\\0.1 & 0.18 & 0.26 & 0.09\\\\0.1 & 0.22 & 0.0 & 0.0\\end{matrix}\\right]$" 399 | ], 400 | "text/plain": [ 401 | "⎡0.1 0.01 0.02 0.0 ⎤\n", 402 | "⎢ ⎥\n", 403 | "⎢0.1 0.0 0.0 0.0 ⎥\n", 404 | "⎢ ⎥\n", 405 | "⎢0.1 0.0 0.03 0.07⎥\n", 406 | "⎢ ⎥\n", 407 | "⎢0.1 0.17 0.13 0.18⎥\n", 408 | "⎢ ⎥\n", 409 | "⎢0.1 0.0 0.0 0.0 ⎥\n", 410 | "⎢ ⎥\n", 411 | "⎢0.1 0.34 0.33 0.2 ⎥\n", 412 | "⎢ ⎥\n", 413 | "⎢0.1 0.18 0.26 0.09⎥\n", 414 | "⎢ ⎥\n", 415 | "⎣0.1 0.22 0.0 0.0 ⎦" 416 | ] 417 | }, 418 | "metadata": {}, 419 | "output_type": "display_data" 420 | } 421 | ], 422 | "source": [ 423 | "display_matrix(H.round(2))" 424 | ] 425 | }, 426 | { 427 | "cell_type": "markdown", 428 | "metadata": {}, 429 | "source": [ 430 | "The matrix V contains the cash flows.\n", 431 | "\n", 432 | "**Important** \n", 433 | "To simplify the computations, the discounted cashflows are reported at every time steps. \n", 434 | "\n", 435 | "For instance: \n", 436 | "In the third row the final cashflow (0.07) is discounted at every time step, till t=1. \n", 437 | "In the paper, the authors just consider the cashflow (0.07) at time t=3 and the discount is performed at the end of the algorithm." 438 | ] 439 | }, 440 | { 441 | "cell_type": "code", 442 | "execution_count": 18, 443 | "metadata": {}, 444 | "outputs": [ 445 | { 446 | "data": { 447 | "text/latex": [ 448 | "$\\displaystyle \\left[\\begin{matrix}0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.0621 & 0.0659 & 0.07\\\\0.0 & 0.17 & 0.0 & 0.0\\\\0.0 & 0.0 & 0.0 & 0.0\\\\0.0 & 0.34 & 0.0 & 0.0\\\\0.0 & 0.18 & 0.0 & 0.0\\\\0.0 & 0.22 & 0.0 & 0.0\\end{matrix}\\right]$" 449 | ], 450 | "text/plain": [ 451 | "⎡0.0 0.0 0.0 0.0 ⎤\n", 452 | "⎢ ⎥\n", 453 | "⎢0.0 0.0 0.0 0.0 ⎥\n", 454 | "⎢ ⎥\n", 455 | "⎢0.0 0.0621 0.0659 0.07⎥\n", 456 | "⎢ ⎥\n", 457 | "⎢0.0 0.17 0.0 0.0 ⎥\n", 458 | "⎢ ⎥\n", 459 | "⎢0.0 0.0 0.0 0.0 ⎥\n", 460 | "⎢ ⎥\n", 461 | "⎢0.0 0.34 0.0 0.0 ⎥\n", 462 | "⎢ ⎥\n", 463 | "⎢0.0 0.18 0.0 0.0 ⎥\n", 464 | "⎢ ⎥\n", 465 | "⎣0.0 0.22 0.0 0.0 ⎦" 466 | ] 467 | }, 468 | "metadata": {}, 469 | "output_type": "display_data" 470 | } 471 | ], 472 | "source": [ 473 | "display_matrix(V.round(4))" 474 | ] 475 | }, 476 | { 477 | "cell_type": "markdown", 478 | "metadata": {}, 479 | "source": [ 480 | "## References\n", 481 | "\n", 482 | "[1] F. Longstaff, E. Schwartz (2001) \"Valuing American Options by Simulation: A Simple Least-Squares Approach\", The Review of Financial Studies, vol 14-1, pag 113-147. " 483 | ] 484 | } 485 | ], 486 | "metadata": { 487 | "kernelspec": { 488 | "display_name": "Python 3", 489 | "language": "python", 490 | "name": "python3" 491 | }, 492 | "language_info": { 493 | "codemirror_mode": { 494 | "name": "ipython", 495 | "version": 3 496 | }, 497 | "file_extension": ".py", 498 | "mimetype": "text/x-python", 499 | "name": "python", 500 | "nbconvert_exporter": "python", 501 | "pygments_lexer": "ipython3", 502 | "version": "3.7.3" 503 | } 504 | }, 505 | "nbformat": 4, 506 | "nbformat_minor": 2 507 | } 508 | --------------------------------------------------------------------------------