Coder Social home page Coder Social logo

cantaro86 / financial-models-numerical-methods Goto Github PK

View Code? Open in Web Editor NEW
5.3K 136.0 970.0 23.66 MB

Collection of notebooks about quantitative finance, with interactive python code.

License: GNU Affero General Public License v3.0

Jupyter Notebook 98.61% Python 0.88% C 0.07% Makefile 0.01% TeX 0.41% Cython 0.02%
quantitative-finance jupyter-notebooks kalman-filter option-pricing financial-engineering financial-mathematics partial-differential-equations fourier-inversion stochastic-processes stochastic-differential-equations

financial-models-numerical-methods's Introduction

Financial-Models-Numerical-Methods

This is a collection of Jupyter notebooks based on different topics in the area of quantitative finance.

Is this a tutorial?

Almost! :)

This is just a collection of topics and algorithms that in my opinion are interesting.

It contains several topics that are not so popular nowadays, but that can be very powerful. 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.
The aim of these notebooks is to present these interesting topics, by showing their practical application through an interactive python implementation.

Who are these notebooks for?

Not for absolute beginners.

These topics require a basic knowledge in stochastic calculus, financial mathematics and statistics. A basic knowledge of python programming is also necessary.

In these notebooks I will not explain what is a call option, or what is a stochastic process, or a partial differential equation.
However, every time I will introduce a concept, I will also add a link to the corresponding wiki page or to a reference manual. In this way, the reader will be able to immediately understand what I am talking about.

These notes are for students in science, economics or finance who have followed at least one undergraduate course in financial mathematics and statistics.
Self-taught students or practicioners should have read at least an introductiory book on financial mathematics.

Why is it worth to read these notes?

First of all, this is not a book!
Every notebook is (almost) independent from the others. Therefore you can select only the notebook you are interested in!

- Every notebook contains python code ready to use!     

It is not easy to find on internet examples of financial models implemented in python which are ready to use and well documented.
I think that beginners in quantitative finance will find these notebooks very useful!

Moreover, Jupyter notebooks are interactive i.e. you can run the code inside the notebook. This is probably the best way to study!

If you open a notebook with Github or NBviewer, sometimes mathematical formulas are not displayed correctly. For this reason, I suggest you to clone/download the repository.

Is this series of notebooks complete?

No!
I will upload more notebooks from time to time.

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.

If you have any kind of questions, or if you find some errors, or you have suggestions for improvements, feel free to contact me.

Contents

1.1) Black-Scholes numerical methods (lognormal distribution, change of measure, Monte Carlo, Binomial method).

1.2) SDE simulation and statistics (paths generation, Confidence intervals, Hypothesys testing, Geometric Brownian motion, Cox-Ingersoll-Ross process, Euler Maruyama method, parameters estimation)

1.3) Fourier inversion methods (inversion formula, numerical inversion, option pricing, FFT, Lewis formula)

1.4) SDE, Heston model (correlated Brownian motions, Heston paths, Heston distribution, characteristic function, option pricing)

1.5) SDE, Lévy processes (Merton, Variance Gamma, NIG, path generation, parameter estimation)

2.1) The Black-Scholes PDE (PDE discretization, Implicit method, sparse matrix tutorial)

2.2) Exotic options (Binary options, Barrier options, Asian options)

2.3) American options (PDE, Early exercise, Binomial method, Longstaff-Schwartz, Perpetual put)

3.1) Merton Jump-Diffusion PIDE (Implicit-Explicit discretization, discrete convolution, model limitations, Monte Carlo, Fourier inversion, semi-closed formula )

3.2) Variance Gamma PIDE (approximated jump-diffusion PIDE, Monte Carlo, Fourier inversion, Comparison with Black-Scholes)

3.3) Normal Inverse Gaussian PIDE (approximated jump-diffusion PIDE, Monte Carlo, Fourier inversion, properties of the Lévy measure)

4.1) Pricing with transaction costs (Davis-Panas-Zariphopoulou model, singular control problem, HJB variational inequality, indifference pricing, binomial tree, performances)

4.2) Volatility smile and model calibration (Volatility smile, root finder methods, calibration methods)

5.1) Linear regression and Kalman filter (market data cleaning, Linear regression methods, Kalman filter design, choice of parameters)

5.2) Kalman auto-correlation tracking - AR(1) process (Autoregressive process, estimation methods, Kalman filter, Kalman smoother, variable autocorrelation tracking)

5.3) Volatility tracking (Heston simulation, hypothesis testing, distribution fitting, estimation methods, GARCH(1,1), Kalman filter, Kalman smoother)

6.1) Ornstein-Uhlenbeck process and applications (parameters estimation, hitting time, Vasicek PDE, Kalman filter, trading strategy)

7.1) Classical MVO (mean variance optimization, quadratic programming, only long and long-short, closed formula)

A.1) Appendix: Linear equations (LU, Jacobi, Gauss-Seidel, SOR, Thomas)

A.2) Appendix: Code optimization (cython, C code)

A.3) Appendix: Review of Lévy processes theory (basic and important definitions, derivation of the pricing PIDE)

How to run the notebooks

Virtual environment: Here I explain how to create a virtual environment with Anaconda and with the python module venv.

  • Option 1:

You can recreate my tested conda virtual environment with:

conda env create -f environment.yml
pip install -e .

The first line recreates the virtual environment and installs all the packages.
With the second line we just install the local package FMNM.

  • Option 2:

If you want to create a new environment with the latest python version, you can do:

conda create -n FMNM python
conda activate FMNM
PACKAGES=$(tr '\n' ' ' < list_of_packages.txt | sed "s/arch/arch-py/g")
conda install ${PACKAGES[@]}
pip install -e .

where in the third line we replace the package name arch with the arch-py, which is the name used by conda.

  • Option 3:

If you prefer to create a venv that uses python 3.11.4, you can do it as follows:

python3.11.4 -m venv --prompt FMNM python-venv
source python-venv/bin/activate
python3 -m pip install --upgrade pip
pip install --requirement requirements.txt
pip install -e .
  • Option 4:

If you prefer to use the python version already installed in your system, you just need to run

pip install --requirement list_of_packages.txt
pip install -e .

and then enter in the shell:

jupyter-notebook

However, if you are using old versions, there could be compatibility problems.

Enjoy!

financial-models-numerical-methods's People

Contributors

cantaro86 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

financial-models-numerical-methods's Issues

A posteriori chosen variances for alpha and beta (Kalman Linear Regression)

Dear cantaro86,

Could you, please, clarify how you chose variances for alpha and beta. You chose the variances for alpha and beta 1e-7 and 1e-2, correspondingly, by "looking at the plot". Do you estimate them in the following way:
(ret_test["ols_alpha"] - ret_test["ols_alpha"].shift(1)).iloc[1:].var()
and
(ret_test["ols_beta"] - ret_test["ols_beta"].shift(1)).iloc[1:].var()
?
In this case I got 0.0033 and 7e-8. Do you round those numbers to get 1e-7 and 1e-2?

Heston pricing model confusion

def cf_Heston(u, t, v0, mu, kappa, theta, sigma, rho):
"""
Heston characteristic function as proposed in the original paper of Heston (1993)
"""
xi = kappa - sigma * rho * u * 1j
d = np.sqrt(xi2 + sigma2 * (u2 + 1j * u))
g1 = (xi + d) / (xi - d)
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)))
+ (v0 / sigma**2) * (xi + d) * (1 - np.exp(d * t)) / (1 - g1 * np.exp(d * t))
)
return cf

limit_max = 1000 # right limit in the integration
call = S0 * Q1(k, cf_H_b_good, limit_max) - K * np.exp(-r * T) * Q2(k, cf_H_b_good, limit_max)
print("Heston Fourier inversion call price: ", call)

when call 'call' function, I need to use Q1 and Q2. but in Q1, cf function only has one input like 'u - 1j'. But here it should be cf_Heston function with 7 inputs. Not sure how did you run out with just one input?

Also the cf formula in cf_Heston, wouldn't it be:

1j * u * mu * t => 1j * u * log(K), K is strike price.


def Q1(k, cf, right_lim):
"""
P(X<k) - Probability to be in the money under the stock numeraire.
cf: characteristic function
right_lim: right limit of integration
"""

def integrand(u):
    return np.real((np.exp(-u * k * 1j) / (u * 1j)) * cf(u - 1j) / cf(-1.0000000000001j))

return 1 / 2 + 1 / np.pi * quad(integrand, 1e-15, right_lim, limit=2000)[0]

CalledProcessError: Command '['cmake', '--version']' returned non-zero exit status 1.

Hi all!

I am trying to run these fantastic notebooks but I constantly have the same issue when trying to create virtual environments or when just trying to install list_of_packages.txt, as instructed in the README.md

I am on macOS Ventura, M2 chip.

My issue is similar to that of Issue #10 but is a bit worse, it seems. Let me explain:

  1. Let's consider one of the possible options for creating an environment. Say, we follow Option 2 (create a new environment with the latest Python version) as presented in the README.md.
  2. One has to run the following code in the terminal: conda create -n FMNM python conda activate FMNM PACKAGES=$(tr '\n' ' ' < list_of_packages.txt | sed "s/arch/arch-py/g") conda install ${PACKAGES[@]} pip install -e .
  3. I set up the right directory in the terminal (I have a copy of the notebook in a folder on my desktop).
  4. Given the Issue #10, I also installed CMake pip install CMake and I verified the version with cmake --version (version 3.27.2)
  5. Now, hoping that all goes well, I decide to run the code of point (3.) but then I get the following subprocess error:

"subprocess.CalledProcessError: Command '['cmake', '--version']' returned non-zero exit status 1."
(some line above this message, I get "Building wheel for qdldl did not run successfully")

I am not 100% sure what this means, but I can't proceed with the installation.
Does any of you have an idea of what the issue could be? I am aware that is a very specific issue, but any suggestion is welcome!

Thank you in advance!

cython problem

Hi, on my new windows 10 laptop, I installed all packages in requirements.txt and ran the cython build. Following your response to another issue I also installed visualcppbuildtools_full.exe.

(FMNM) C:\Users\x\Documents\FMNM>cd functions/cython
(FMNM) C:\Users\x\Documents\FMNM\functions\cython>python setup.py build_ext --inplace
running build_ext
running build_ext
(FMNM) C:\Users\x\Documents\FMNM\functions\cython>

When I run the imports at the start of 1.4 SDE - Heston model in Anaconda Jupyter, I get following error:


ModuleNotFoundError Traceback (most recent call last)
in
8 from functools import partial
9 from functions.probabilities import Heston_pdf, Q1, Q2
---> 10 from functions.cython.cython_Heston import Heston_paths_log, Heston_paths
11 from scipy.optimize import minimize
12

ModuleNotFoundError: No module named 'functions.cython.cython_Heston'

but that module is in the functions directory.

I am puzzled as I installed FMNM and ran 1.4 without problem on a ubuntu virtualbox even though I had not installed visualcppbuildtools_full.exe on it.

NoteBook 1.4

Hello

Firstly thanks so much for all your notebooks they are really helpful and insightful. Credit to you for all the effort.

However I noticed something in notebook 1.4

When you are generating rice paths using Hestons Model you use the following equation :

for t in range(0,N-1):
    v = np.exp(Y[:,t])    # variance 
    v_sq = np.sqrt(v)     # square root of variance 
    
    Y[:,t+1] = Y[:,t] + (1/v)*( kappa*(theta - v) - 0.5*sigma**2 )*dt + sigma * (1/v_sq) * dt_sq * W_v[:,t]   

    X[:,t+1] = X[:,t] + (mu - 0.5*v)*dt + v_sq * dt_sq * W_S[:,t]

However, According to Euler Method shoulndt it be as follows:
for i in range(1,N+1): S[i] = S[i-1] * np.exp( (mu- 0.5*v[i-1])*dt + np.sqrt(v[i-1] * dt) * Z[i-1,:,0] ) v[i] = np.maximum(v[i-1] + kappa*(theta-v[i-1])*dt + sigma*np.sqrt(v[i-1]*dt)*Z[i-1,:,1],0)
I could be wrong but just thought id check

Installing on Windows 10

Apologies for being a windows newbie :P However, I would love to tinker with some of these tools.

First, I tried downloading Docker and running python docker_start_notebook.py both from Powershell as Admin and my Anaconda console. Both generated errors at line 18:

UID =

I did a bit of Googling and substituted in:
UID = '{}:{}'.format(os.getuid(), os.getgid()
which seemed to work only to get stuck at line 19 with a syntax error :P

Then I tried compiling the cython functions manually using
python setup.py build_ext --inplace
And was given:

running build_ext
building 'cython_functions' extension
error: Unable to find vcvarsall.bat

I'd much prefer to get this working on my normal Jupyter setup by compiling the functions and being able to import them into my notebooks. Any tips?

One more tidbit, if I try to run setup.py from Visual Studio Code I get:

File "c:..../Financial-Models-Numerical-Methods/functions/cython/setup.py", line 21, in
ext_modules = cythonize("cython_functions.pyx", language_level='3'),
File "C:\Users\Rishan\anaconda3\lib\site-packages\Cython\Build\Dependencies.py", line 971, in cythonize
aliases=aliases)
File "C:\Users\Rishan\anaconda3\lib\site-packages\Cython\Build\Dependencies.py", line 815, in create_extension_list
for file in nonempty(sorted(extended_iglob(filepattern)), "'%s' doesn't match any files" % filepattern):
File "C:\Users\Rishan\anaconda3\lib\site-packages\Cython\Build\Dependencies.py", line 114, in nonempty
raise ValueError(error_msg)
ValueError: 'cython_functions.pyx' doesn't match any files

installation fails in python 3.11

/content/Financial-Models-Numerical-Methods# pip3 install -e .
Obtaining file:///content/Financial-Models-Numerical-Methods
Installing build dependencies ... done
Checking if build backend supports build_editable ... done
Getting requirements to build editable ... done
Installing backend dependencies ... done
Preparing editable metadata (pyproject.toml) ... done
Requirement already satisfied: arch in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (6.1.0)
Requirement already satisfied: cvxpy in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.3.2)
Requirement already satisfied: cython in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (0.29.36)
Requirement already satisfied: jupyter in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.0.0)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (3.7.1)
Requirement already satisfied: numpy in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.23.5)
Requirement already satisfied: pandas in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.5.3)
Requirement already satisfied: scikit-learn in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.2.2)
Requirement already satisfied: scipy in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.10.1)
Requirement already satisfied: seaborn in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (0.12.2)
Requirement already satisfied: statsmodels in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (0.14.0)
Requirement already satisfied: sympy in /usr/local/lib/python3.10/dist-packages (from FMNM==1.0.0) (1.12)
INFO: pip is looking at multiple versions of fmnm to determine which version is compatible with other requirements. This could take a while.
ERROR: Package 'fmnm' requires a different Python: 3.10.12 not in '>=3.11'

ERROR: Failed building wheel for qdldl

like the title suggested, I had issue running option 3
python3.11.4 -m venv --prompt FMNM python-venv source python-venv/bin/activate python3 -m pip install --upgrade pip pip install --requirement requirements.txt pip install -e .

my python version is 3.11.4
I cloned the repo to local
the environment is MacOS Ventura M1 MacBook Air

I have a very limited debugging experience.
So I googled the error and found stack overflow had similar question and I attempted the solution but was not able to solve the issue.

I appreciate any help in advance

Loops over columns vs loops over rows

For loops over rows is faster than over columns.

I have already updated the code in commit 8fe948e, where this code:

X = np.zeros((paths, N))
for t in range(0, N - 1):
    X[:, t + 1] = self.theta + np.exp(-self.kappa * dt) * (X[:, t] - self.theta) + std_dt * W[:, t]

was replaced by this:

X = np.zeros((N, paths))
for t in range(0, N - 1):
    X[t + 1, :] = self.theta + np.exp(-self.kappa * dt) * (X[t, :] - self.theta) + std_dt * W[t, :]  

(there was no need to swap rows and cols where the code was vectorized and there are no for loops)

To improve the speed, we should invert rows and columns in each PDE solver. There are many PDEs in this repo, so it is long and hard work. I'm not going to work on this shortly.

In addition to swapping the columns with the rows, we also need to place boundary conditions in different positions inside the matrix.
For instance, for a problem that goes backward in time (such as the BS PDE in notebook 2.1), I used to define the terminal BC in the last column. In the new version, the "terminal BC" should be placed in the last row.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.