PyQL Documentation

repository·master·Indexed 23 days ago

https://github.com/enthought/pyql

PyQL provides Cython-based wrappers for the QuantLib quantitative finance library, enabling high-performance Pythonic access to QuantLib objects. It supports Python 2 and 3, requiring QuantLib 1.5 to 1.8 and Cython 0.24.1 or higher. The library includes modules for handling Dates, Periods, Calendars, Business Day Conventions, Day Counters, and Schedules, while abstracting C++ memory management like shared_ptr and Handle.

Tokens
11.2K
Snippets
25
Records
49
Agent score
79%

What's inside PyQL

  1. Overview of PyQL capabilities

    master
    PyQL is a set of Cython wrappers for the QuantLib library. It is designed to provide Pythonic access to QuantLib objects. Currently, the library focuses on providing wrappers for fundamental objects such as Date and Calendar, with potential for future expansion into more complex QuantLib components. It supports both Python 2 and Python 3.
  2. Use the mlab module for high-level quantitative finance calculations

    master
    The mlab module provides high-level functions designed for performing common quantitative finance calculations with minimal data transformation. It is built around the use of standardized data structures, allowing users to easily string different functions together in a pipeline.
  3. What is a Market in PyQL?

    master

    Because PyQL wraps QuantLib, users often face an overwhelming number of market convention parameters. To simplify this, PyQL introduces the Market abstraction.

    A Market acts as a virtual trading place that encapsulates all the conventions required for financial calculations. It serves two primary purposes:

    1. Repository of Trading Conventions: It stores the business day calendars and daycount conventions relevant to that specific market (e.g., US Treasury, Euribor, or US Equity).
    2. Standard Calculations: It provides high-level methods for performing calculations based on the market type. For Fixed Income markets, this includes bootstrapping yield curves from market quotes and calculating discount factors directly.

    By using a Market object, you can perform complex QuantLib operations without manually specifying every individual convention parameter.

  4. Manage C++ references using shared_ptr

    master

    To prevent memory leaks and segmentation faults, all Cython extension references must be declared using shared_ptr.

    Crucial Rule: When receiving a shared_ptr reference, never assign the target pointer to a local raw pointer variable, as the object might be deallocated. Instead, always use the shared_ptr copy constructor to create a local, stack-allocated copy of the shared_ptr itself.

  5. Use Periods for date arithmetic

    master

    A Period represents a span of time and is used to shift dates. You can create a Period using a frequency or a specific length with time units.

    Time Units:

    • Days, Weeks, Months, Years

    Frequencies:

    • NoFrequency, Once, Annual, Semiannual, EveryFourthMonth, Quartely, Bimonthly, Monthly, EveryFourthWeek, Biweekly, Weekly, Daily, OtherFrequency.
  6. Apply Business Day Conventions for date adjustment

    master

    When a transaction date falls on a non-business day, you must adjust it using a BusinessDayConvention. These are available in the calendar module:

    • Following: The first following business day.
    • ModifiedFollowing: The first following business day unless it falls in the next month, in which case it uses the first preceding business day.
    • Preceding: The first preceding business day.
    • ModifiedPreceding: The first preceding business day unless it falls in the previous month, in which case it uses the first following business day.
    • Unadjusted: No adjustment is made.
  7. Understand the Risk-free Rate and Dividends data structure

    master
    The riskfree_dividend data structure represents the implied term structure of the risk-free rate and dividend yield. When calibrating a volatility model, the default algorithm computes this structure from option data using the call-put parity relationship.
  8. Understand the PyQL API design philosophy

    master

    The PyQL API is designed to mirror the original QuantLib C++ source as closely as possible while providing Pythonic access to classes, methods, and functions.

    To simplify usage, PyQL abstracts away complex C++ memory management structures. Specifically, types like std::shared_ptr and Handle are handled automatically at the Python layer, so you do not need to manage them explicitly when interacting with the library.

  9. PyQL Core Concepts and Features

    master

    PyQL is a thin, Pythonic layer built on top of QuantLib using Cython. It is designed to overcome the limitations of SWIG wrappers by providing better integration and a cleaner API.

    Key Features

    • Pythonic Integration: Seamless integration with standard Python datatypes (like datetime objects) and numpy arrays.
    • Simplified API: High-level abstractions that hide complex C++ details (e.g., usage of Handles is completely hidden from the user).
    • Improved Developer Experience:
      • Full docstrings and detailed function signatures available on the Python side.
      • Code is organized into subpackages that mirror the C++ organization, providing a clean namespace.
      • Faster build times for new functionalities due to the Cython-based architecture.
    • Documentation: Full support for Sphinx documentation.
  10. Launch PyQL sample notebooks using IPython

    master

    You can view and interact with the sample notebooks by launching the IPython notebook server with --pylab inline enabled.

    Use the following command structure:

    ipython notebook --pylab inline <path to the notebooks folder> --browser=<browser name>

    Example (Linux/Firefox): If your project is located in ~/dev, use:

    ipython notebook --pylab inline ~/dev/pyql/examples/notebooks --browser=firefox
  11. Use the names module to reference column names

    master

    To ensure interoperability and avoid errors from hardcoded strings, always reference column names using the variables defined in the quantlib.reference.names module. Instead of using string literals like 'Strike', use the corresponding constant from the names module.

    import quantlib.reference.names as nm
    strike = option_quotes[nm.STRIKE]
  12. Declare the C++ class in a .pxd file

    master

    The _foo.pxd file is used to declare the external C++ class. You use cdef extern from to point to the C++ header file and specify the namespace. The syntax closely follows C++ declaration style. Types used in arguments should be imported from quantlib.types.

    Example for SimpleQuote inheriting from Quote:

    from quantlib.types cimport Real
    from quantlib._quote cimport Quote
    
    cdef extern from 'ql/quotes/simplequote.hpp' namespace 'QuantLib':
    
       cdef cppclass SimpleQuote(Quote):
          SimpleQuote(Real value)
          Real setValue(Real value)
          void reset()