A brief introduction to the QuantLib in Python…

QuantLib is an open-source framework for quantitative finance  written in C++. There is an active community who develop and extend the library. QuantLib covers a wide range of financial instruments and markets like IR, FX and Equities and provide pricing engines and models, optimization algorithm, a Monte-Carlo framework, business day conventions, day count conventions, holidays calendars and even more… and grows continuously.

There are existing interfaces to different language like Python, Ruby, Java and more via swig. In the following I will describe how to build the QuantLib for Python.

In the following description I assume that you have already installed Python with IPython including all dependencies, numpy, scipy, pandas and matplotlib. A good starting point are distributions like Anaconda or WinPython (for Windows only). These distribution are shipped with many more useful libraries and provide an easy way to install more packages. Its worth to check them out, if haven’t tried them yet.

For windows you can find pre-build executables of the QuantLib at Christoph Gohlke’s website. If you want to have the most recent version you should clone the current master branch from GitHub and build the library and the python package yourself.

To build QuantLib from sources under Windows you need the correct Visual Studio depending on the Python version you are targeting. For Python 3.3 you need Visual Studio 2010 and for Python 2.7 you need Visual Studio 2008. Additional dependencies are the boost library and swig.

I will not cover how to install the dependencies but you can find binary installer for swig under windows on the swig project website and there also exists precompiled binaries for the boost library on source forge. Add the path to swig command to your PATH environment variable.

The following steps are valid for Python 2.7 and 3.3:

0. Clone the git repository either with using git:

cd c:\path\to\quantlib
git clone https://github.com/lballabio/quantlib .

or download as a zipped file from GitHub.

1. Open the QuantLib_vcXX.sln and build it in “Release” or “Release static runtime” configuration. For more details check the install documentation on the QuantLib project site. You will find the solution under


2. Open command line window and set required environment variables

SET QL_DIR=c:\path\to\quantlib\QuantLib
SET INCLUDE=c:\path\to\boost;%INCLUDE%
SET LIB=c:\path\to\boost\lib;%LIB%

3. Create the interface code with swig

cd c:\path\to\quantlib\QuantLib-SWIG\python
python setup.py wrap

4. Build and install the package

python setup.py build
python setup.py install

5. Test your install

python setup.py test

If you use Visual Studio 2010 and target Python 2.7 you will encounter the error message “Unable to find vcversall.bat“. The following “hack” works for me:

Set an additional environment variable at step 2:


Under unix you can also find some pre-build packages (e.g. for Ubuntu) in your package-manager or you build it from sources yourself with the usual configure, make and make install chain (see here and for Mac OS X here). After you build the library you can continue with step 3 above. Be sure you have installed swig before. Just download the source from the swig project and install via the usual unix install commands.

After we have managed to install QuantLib Python package I want to show you how you can use the QuantLib C++ classes from Python. You can download the following simple example  from my repository “IPythonScripts” on GitHub.

In the first example we will see how to setup an interest rate swap and use a discounting pricing engine to calculate the NPV and the fair rate for this swap.

First we need to import the QuantLib package, since we want also produce some plots we import numpy and matplotlib.

import numpy as np
import matplotlib.pyplot as plt
import QuantLib as ql

In the next step we will setup the yield curve (aka yieldtermstructure). For simplicity we will use an flat forward curve. I will use the same curve for discounting and calculation of the forwards. QuantLib supports multi curve setups, as I will maybe show in a later post or you can see in the examples how to setup more realistic yield curves.

# Set Evaluation Date
today = ql.Date(31,3,2015)
# Setup the yield termstructure
rate = ql.SimpleQuote(0.03)
rate_handle = ql.QuoteHandle(rate)
dc = ql.Actual365Fixed()
disc_curve = ql.FlatForward(today, rate_handle, dc)
hyts = ql.YieldTermStructureHandle(disc_curve)

The yieldTermStructure object provides an method which gives us the discount factor for a particular date (QuantLib.Date object) or time in years (with 0 = evaluationDate). This method is called discount.  I am using the numpy method vectorize to apply this function on arrays or list of times and then generate a plot of the discount curve.

discount = np.vectorize(hyts.discount)
tg = np.arange(0,10,1./12.)
plt.plot(tg, discount(tg))
plt.ylabel("discount factor")
plt.title("Flat Forward Curve")


In the next step we will setup up a plain vanilla EURIBOR 6M Swap with maturity in 10 years. Therefore we generate an index and using the handle to our yield curve as forward curve and two schedules, one for the fixed rate leg with annual payments and one for the float leg with semi annual payments.

start = ql.TARGET().advance(today, ql.Period("2D"))

end = ql.TARGET().advance(start, ql.Period("10Y"))

nominal = 1e7

typ = ql.VanillaSwap.Payer

fixRate = 0.03

fixedLegTenor = ql.Period("1y")

fixedLegBDC = ql.ModifiedFollowing

fixedLegDC = ql.Thirty360(ql.Thirty360.BondBasis)

index = ql.Euribor6M(ql.YieldTermStructureHandle(disc_curve))

spread = 0.0

fixedSchedule = ql.Schedule(start, end, fixedLegTenor, index.fixingCalendar(), fixedLegBDC, fixedLegBDC, ql.DateGeneration.Backward, False)
floatSchedule = ql.Schedule(start, end, index.tenor(), index.fixingCalendar(), index.businessDayConvention(), index.businessDayConvention(), ql.DateGeneration.Backward, False)

swap = ql.VanillaSwap(typ, nominal, fixedSchedule, fixRate, fixedLegDC, floatSchedule, index, spread, index.dayCounter())

The last step before we can calculate the NPV we need a pricing engine. We are going to use the discountingSwapEngine. As the name suggests, it will discount all future payments to the evaluation date and calculate the difference between the present values of the two legs.

engine = ql.DiscountingSwapEngine(ql.YieldTermStructureHandle(disc_curve))


That was a very brief demonstration of the QuantLib. The examples which are shipped with the QuantLib give a much more detailed insight. So you may have a look on these.


One thought on “A brief introduction to the QuantLib in Python…

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s