Giter VIP home page Giter VIP logo

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

View Code? Open in Web Editor NEW
5.3K 135.0 955.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

Hi there ๐Ÿ‘‹

watching_count

My name is Nicola Cantarutti.
I am originally from Gorizia, a small town in northern Italy. Currently, I am living in Switzerland.
I am passionate about mathematics, statistics, quantitative finance, and science.

Check out my second account, where I develop mathematical methods for neuroscience libraries: nico_canta.

Outside of the work context, I am interested in many other things such as traveling, football, motorcycles, history, manga, crypto trading, and DeFi.

Do you want to contact me? LinkedIn

My GitHub Stats

github stats

ovi

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

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.

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.

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]

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'

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!

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

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

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.