Giter VIP home page Giter VIP logo

domokane / financepy Goto Github PK

View Code? Open in Web Editor NEW
1.9K 63.0 289.0 63.09 MB

A Python Finance Library that focuses on the pricing and risk-management of Financial Derivatives, including fixed-income, equity, FX and credit derivatives.

Home Page: https://financepy.com/

License: GNU General Public License v3.0

Python 22.35% Jupyter Notebook 77.65% Batchfile 0.01%
risk pricing risk-management asset-allocation finance valuation python derivatives-pricing numba bonds

financepy's Introduction

I'D LIKE YOUR OPINION

I AM CONSIDERING SPENDING TIME THIS YEAR IMPROVING THE LIBRARY. LET ME HAVE ANY COMMENTS, REQUESTS OR ISSUES YOU MAY HAVE. JUST ENTER THEM IN THE DISCUSSION SECTION HERE OR EMAIL ME.

Latest News and Version

19 February 2024 version 0.350 released

  • A lot of various pep8 fixes - should all be nearly done soon
  • Fixed a bug in gauss_approx_tranche_loss

9 December 2023 version 0.34 released

  • A lot of various pep8 fixes - should all be nearly done soon
  • Some minor bug fixes

10 November 2023 version 0.33 released

  • Tidied up key rate code
  • Fixed unit tests for pytest
  • Fixed vectorisation of barrier options
  • Various pep8 fixes

28 August 2023 - version 0.32 released

  • Fixed bug in Bond OAS and ASW

24 August 2023 - Version 0.31 released

Schedule

  • Corrected bug in schedule generation
  • Corrected bug in CDS protection leg integral

Many Bond Classes have been amended

  • Changed FULL price to DIRTY price in functions UPDATE YOUR CODE PLEASE. APOLS for inconvenience.
  • Removed face amount from bond class - how much you buy is not intrinsic to a bond
  • Made number of ex-dividend days a member of bond class
  • Added adjustment for ex-dividend dates to yield calculations
  • Revised accrued and principal functions to take face amount as input
  • Updated document

29 May 2023 - Version 0.30 released

  • Added PrettyPrint to required dependencies

22 Nov 22 Version 0.260 has been released and pushed to PyPI

  • Create Date from python datetime
  • Zero coupon bond class
  • Fixed bug in bond payment date

31-Aug-2022 Version 0.240 has just been released and pushed to PyPI with changes

  • Negative terms in date class
  • Recovery rates do not default to standard value for CDS curves

DISCLAIMER

This software is distributed FREE AND WITHOUT ANY WARRANTY.

Report any bugs or suggestions here as an issue.

CONTRIBUTORS WANTED !

If you have a knowledge of Quantitative Finance and a reasonable knowledge of Python, then please consider contributing to this project. There are small tasks and big tasks to be done. Just look in the list of Issues and you may find something you can do. Before you begin, please comment in the issue thread in case someone else may be working on that issue. Or you can contact me directly at dominic.okane at edhec.edu.

If you are a user and require some additional functionality, then please add it as an issue.

Quick Start Guide

FinancePy can be installed from pip using the following command:

pip install financepy

To upgrade an existing installation type:

pip install --upgrade financepy

I have encountered problems using Anaconda3-2020.07 due to some Numba and LLVMLite problems. However, Anaconda3-2020.02 works.

Using FinancePy in a Jupyter Notebook

Once financepy has been installed, it is easy to get started.

Just download the project and examine the set of Jupyter Notebooks in the notebook folder.

A pdf manual describing all the functions can be found in the project directory.

Overview

FinancePy is a python-based library that is currently in beta version. It covers the following functionality:

  • Valuation and risk models for a wide range of equity, FX, interest rate and credit derivatives.

Although it is written entirely in Python, it can achieve speeds comparable to C++ by using Numba. As a result the user has both the ability to examine the underlying code and the ability to perform pricing and risk at speeds which compare to a library written in C++.

The target audience for this library includes:

  • Students of finance and students of python
  • Academics teaching finance or conducting research into finance
  • Traders wishing to price or risk-manage a derivative.
  • Quantitative analysts seeking to price or reverse engineer a price.
  • Risk managers wishing to replicate and understand price sensitivity.
  • Portfolio managers wishing to check prices or calculate risk measures.
  • Fund managers wanting to value a portfolio or examine a trading strategy.

Users should have a good, but not advanced, understanding of Python. In terms of Python, the style of the library has been determined subject to the following criteria:

  1. To make the code as simple as possible so that those with a basic Python fluency can understand and check the code.
  2. To keep all the code in Python so users can look through the code to the lowest level.
  3. To offset the performance impact of (2) by leveraging Numba to make the code as fast as possible without resorting to Cython.
  4. To make the design product-based rather than model-based so someone wanting to price a specific product can easily find that without having to worry too much about the model โ€“ just use the default โ€“ unless they want to. For most products, a Monte-Carlo implementation has been provided both as a reference for testing and as a way to better understand how the product functions in terms of payments, their timings and conditions.
  5. To make the library as complete as possible so a user can find all their required finance-related functionality in one place. This is better for the user as they only have to learn one interface.
  6. To avoid complex designs. Limited inheritance unless it allows for significant code reuse. Some code duplication is OK, at least temporarily.
  7. To have good documentation and easy-to-follow examples.
  8. To make it easy for interested parties to contribute.

In many cases the valuations should be close to if not identical to those produced by financial systems such as Bloomberg. However for some products, larger value differences may arise due to differences in date generation and interpolation schemes. Over time it is hoped to reduce the size of such differences.

Important Note:

  • IF YOU HAVE ANY PRICING OR RISK EXAMPLES YOU WOULD LIKE REPLICATED, SEND SCREENSHOTS OF ALL THE UNDERLYING DATA, MODEL DETAILS AND VALUATION.
  • IF THERE IS A PRODUCT YOU WOULD LIKE TO HAVE ADDED, SEND ME THE REQUEST.
  • IF THERE IS FUNCTIONALITY YOU WOULD LIKE ADDED, SEND ME A REQUEST.

The Library Design

The underlying Python library is split into a number of major modules:

  • Utils - These are utility functions used to assist you with modelling a security. These include dates (Date), calendars, schedule generation, some finance-related mathematics functions and some helper functions.
  • Market - These are modules that capture the market information used to value a security. These include interest rate and credit curves, volatility surfaces and prices.
  • Models - These are the low-level models used to value derivative securities ranging from Black-Scholes to complex stochastic volatility models.
  • Products - These are the actual securities and range from Government bonds to Bermudan swaptions.

Any product valuation is the result of the following data design:

VALUATION = PRODUCT + MODEL + MARKET

The interface to each product has a value() function that will take a model and market to produce a price.

Author

Dominic O'Kane. I am a Professor of Finance at the EDHEC Business School in Nice, France. I have 12 years of industry experience and over 15 years of academic experience.

Contact me at dominic.okane at edhec.edu.

Dependencies

FinancePy depends on Numpy, Numba, Scipy and basic python libraries such as os, sys and datetime.

Changelog

See the changelog for a detailed history of changes.

Contributions

Contributions are very welcome. There are a number of requirements:

  • The code should be Pep8 compliant.
  • Comments are required for every class and function, and they should be a clear description.
  • At least one broad test case and a set of unit tests must be provided for every function.
  • Avoid very pythonic constructions. For example a loop is as good as a list comprehension. And with numba it can be faster. Readability is the priority.

License

GPL-3.0 License - See the license file in this folder for details.

financepy's People

Contributors

abhi-g80 avatar ameyshrivastava avatar cclauss avatar dependabot[bot] avatar dominichong avatar domokane avatar fergalok avatar gpelleri avatar idorrington92 avatar jtamas18 avatar mattyuan98 avatar mayank1897 avatar nashquant avatar piterbarg avatar poornagurram avatar rkcah avatar ryanrussell avatar saeedamen avatar sagayev avatar shunmaruko avatar vfermat 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

financepy's Issues

solveforsmilestrike

Once I have a FxVolSurface object calibrated I am trying to retrieve the Strike corresponding to a set deltaTarget and ExpiryDate. This would be used to price a fxVanillaOption with specified delta as input instead of specified strike.

#Issue 1
This function doesn't seem to exist in the class functions with only 2 args as parameters (self, deltaTarget as float,ExpiryDate as FinDate).

#Issue 2 (alternative using solveForSmileStrike)
solveForSmileStrike seem to do the job but only for specific Expiry dates. However in FinFXVolSurfacePlus the function solveForSmileStrike takes into parameters:
OptionTypeValue
deltaTarget
tenorIndex
initialValue

This currently returns an error probably because the args (strikes = args[9] and gaps = args[10]) are not specified when calling deltaFit

Curve Building OIS and IBOR

You'll need to offer curve calibration using outright OIS & IBOR tenor swaps, OIS meeting date swaps, basis swaps of either IBOR/IBOR, IBOR/OIS or OIS/OIS, OIS and IBOR futures, IBOR FRAs (I include ESTR and SOFR in the OIS category). You should also allow for multiple overnight rates per currency (SOFR+FF & ESTR+EONIA).

The most interesting case to cover is probably AUD where you need full multi-curve support as the 3m and 6m curves are co-dependent on each other.

Few common payoffs missing for FX

Great library!

A few useful payoffs could be added in FX:

  • FinFXOneTouchOption (adaptation of FinEquityOneTouchOption)
  • FinDoubleOneTouchOption & FinDoubleDigitalOption (adaptation of "single" barrier payoffs)
  • FinFXDualOneTouchOption & FinFXDualDigitalOption (would require an additional implied correlation parameter)

All five payoffs are quite commonly used by FX market practitioners as considered "Light exotic".

G10 Calendars

@domokane , awesome work with this package! Great to see everything written in Python.

One feature request - it would be great to get calendars added for the rest of the G10 markets. Could use QL calendars as a reference.

Thanks!

Perpetual Bond

Add perpetual bond type and associated yield and risk measures.

Normal SABR calibration

It would be very helpful to have a normal vol (bachelier) SABR pricing model. I know the bachelier model exists as an alternative to black's, but the SABR formulation is a bit different.

Implied Volatility for Equity Vanilla Options - Numerical issue

The current Equity implied volatility calculator uses Newton Raphson with an analytical first derivative (vega).

This has numerical issues for short-dated ITM options.

Needs to be fixed by converting ITM option to OTM using put call parity and then solving for that option with new implied price.

FinDate Optimisation

FinDate has been implemented with only some Python datetime dependency in a few functions.

However the issue of processing speed is becoming more important.

I would be interested to know which of the following approaches is superior in speed terms.

  1. Make FinDate (which now includes date and time) a thin layer over datetime i.e. all functions should call datetime functions rather than do processing themselves.

or

  1. Make FinDate independent of datetime and do all of the logic in the FinDate class. In this case consider if FinDate should be sped up using numba ? Functions like addDays and addMonths might benefit.

I imagine two implementations of FinDate which can be implemented and compared. Only core functions of date generation and differencing and rolling foward in date steps should be compared as most other functions build on these.

Inflation Linked Bonds

Add inflation linked bond type and associated real and inflation linked yield measures. Test against BBG.

FinDate constructor

Request to overload the FinDate constructor to accept date string and formatting string

Vectorisation of Calculations

Some functions take a date as an input. However I would like to be able to pass in a vector/list of dates and/or a vector of enums and get a corresponding vector of values.

This is shown in notebook

https://github.com/domokane/FinancePy/blob/master/notebooks/products/equity/EQUITY_VANILLA_EUROPEAN_STYLE_OPTION_VECTORISATION.ipynb

Consider f(x,y,z). Behaviour that would be good

  1. If x is an N-element vector and y, z not then f(x,y,z) is an N-element vector for each value of x
  2. If x is an N-element vector and y is an N element vector but z is not then f(x,y,z) is an N-element vector for each value of x,y
  3. If x, y, z are all an N-element vector then f(x,y,z) is an N-element vector for each value of x,y

A generic approach would be best that is easy to modify and relies on a central function that takes as argument the function to be called.

Implied Volatility for FX Options

The current FX implied volatility calculator uses Newton Raphson with an analytical first derivative (vega).

This has numerical issues for short-dated ITM options.

Needs to be fixed by converting ITM option to OTM using put call parity and then solving for that option with new implied price.

Failed Tests

runAllTests.py raises error while testing the master. only two test cases passed. Need to add functionality to check other tests instead of halting if one test fails too.

Testing module TestFinModelRatesBDT (3 out of 90)
Traceback (most recent call last):
  File "tests/runAllTests.py", line 26, in <module>
    moduleName = __import__(moduleTextName)
  File "/home/runner/work/FinancePy/FinancePy/tests/TestFinModelRatesBDT.py", line 284, in <module>
    test_BDTExampleTwo()
  File "/home/runner/work/FinancePy/FinancePy/tests/TestFinModelRatesBDT.py", line 160, in test_BDTExampleTwo
    price = bond.cleanPriceFromDiscountCurve(settlementDate, curve)
  File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/financepy-0.184-py3.8.egg/financepy/products/bonds/FinBond.py", line 320, in cleanPriceFromDiscountCurve
    self.calcAccruedInterest(settlementDate)
  File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/financepy-0.184-py3.8.egg/financepy/products/bonds/FinBond.py", line 443, in calcAccruedInterest
    (accFactor, num, _) = dc.yearFrac(self._pcd,
  File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/financepy-0.184-py3.8.egg/financepy/finutils/FinDayCount.py", line 213, in yearFrac
    freq = FinFrequency(frequencyType)
  File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/site-packages/financepy-0.184-py3.8.egg/financepy/finutils/FinFrequency.py", line 30, in FinFrequency
    if frequencyType in FinFrequencyTypes:
  File "/opt/hostedtoolcache/Python/3.8.5/x64/lib/python3.8/enum.py", line 315, in __contains__
    raise TypeError(
TypeError: unsupported operand type(s) for 'in': 'int' and 'EnumMeta'

Implement numba'd conjugate gradient minimiser

The conjugate gradient descent algorithm in scipy is slow and prevents the calling function from being jitted by numba. Idea is to find a python version of the CG minimiser that can be jitted to give faster minimisations.

FinEquityVolSurface

Hi,

Would it be possible to extend the FinEquityVolCurve class into a Surface:
User Inputs (for S&P 500 on 11 Jan 2021)

  • value Date (ex: FindDate(2021,1,11) )
  • Array of Expires (ex: [FindDate(2021,2,11), FindDate(2021,3,11), FindDate(2021,4,11), FindDate(2021,7,11), FindDate(2021,10,11), FindDate(2022,1,11), FindDate(2023,1,11)])
  • Array of Strikes (ex: [3037 3418 3608 3703 3798 3893 3988 4178 4557])
  • Array of Vols (ex: [42.94 31.30 25.88 22.94 19.72 16.90 15.31 17.54 25.67,
    37.01 28.25 24.19 21.93 19.57 17.45 15.89 15.34 21.15,
    34.68 27.38 23.82 21.85 19.83 17.98 16.52 15.31 18.94,
    31.41 26.25 23.51 22.05 20.61 19.25 18.03 16.01 15.90,
    29.91 25.58 23.21 22.01 20.83 19.70 18.62 16.63 14.94,
    29.26 25.24 23.03 21.91 20.81 19.73 18.69 16.76 14.63,
    27.59 24.33 22.72 21.93 21.17 20.43 19.71 18.36 16.26] )

This would return a VolSurface object. The volatility method would also be extended to take as input a strike and expiry date.

FinEquity...Options dividends input

Looking at Equity products. FinEquityVanillaOption methods for example take as argument for the dividend as a float. Would be nice to have the dividendCurve object passed as argument directly similar to the discountCurve instead of passing dividendCurve.df(self._expiryDate)

Numba specialist to Examine how to JIT Optimisers

Scipy optimisers are used in a number of locations. However it is not been possible to Numba the objection functions.
I have rewritten the optimisers in FinSolver but there are problems using njit
The aim here is to

  1. Numba the optimisers
  2. Numba the objective function
  3. Amend all functions that use Scipy to use FinSolver to use the Numba versions

Overall aim is to make these functions as fast as possible.

BBG Testing Examples

If anyone has access to Bloomberg analytics that I can compare to then please send examples.
Especially with regards to

  • Bonds - bullet, floating rate notes, perpetuals, step-ups, callable, puttable
  • Convertibles - all sorts
  • Options on bonds
  • FRAs
  • Interest rate futures
  • Swaps
  • Cross currency swaps
  • Swap curves construction
  • OIS
  • Caps, floors, swaptions
  • Other exotics
    etc...

Add an Equity Index Option product type

Add a product type for an option on an equity index called FinEquityIndexOption

This is similar to an Equity vanilla option but customised to index options.

The option can be European or American exercise.

The valuation can take in the futures price rather than the spot price.

It also needs an implied volatility calculation.

Most of this can be copied from FinEquityVanillaOption.

As we have index futures contracts, pricing uses Black's model rather than Black-Scholes.

You will need to add a test module and a notebook showing how this product works.

Reference

https://globaljournals.org/GJMBR_Volume12/10-Pricing-of-Index-Options-Using-Blacks-Model.pdf

Swaption Cube Object

Create an object to store volatility by start tenor, swap tenor and strike
Also does interpolation.

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.