Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions quantlib/_interest_rate.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,9 @@
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
"""

include 'types.pxi'

from quantlib.types cimport DiscountFactor, Rate, Real, Time
from libcpp.string cimport string
from quantlib.time._date cimport Date
from quantlib.time._daycounter cimport DayCounter
from quantlib.time._period cimport Frequency
from quantlib.compounding cimport Compounding
Expand All @@ -29,6 +28,10 @@ cdef extern from 'ql/interestrate.hpp' namespace 'QuantLib' nogil:
Frequency frequency()

DiscountFactor discountFactor(Time t)
DiscountFactor discountFactor(const Date& d1,
const Date &d2,
const Date& refStart,
const Date& refEnd)
InterestRate impliedRate(Real compound,
const DayCounter& resultDC,
Compounding comp,
Expand All @@ -39,6 +42,10 @@ cdef extern from 'ql/interestrate.hpp' namespace 'QuantLib' nogil:
Frequency freq,
Time t)
Real compoundFactor(Time t)
Real compoundFactor(const Date& d1,
const Date &d2,
const Date& refStart,
const Date& refEnd)

cdef extern from "<sstream>" namespace "std":
cdef cppclass stringstream:
Expand Down
6 changes: 6 additions & 0 deletions quantlib/instruments/_bond.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ cdef extern from 'ql/instruments/bond.hpp' namespace 'QuantLib' nogil:
Real dirtyPrice() except +
Real settlementValue() except +

Rate cleanPrice(Rate y,
DayCounter& dc,
Compounding comp,
Frequency freq,
Date settlementDate)

Rate bond_yield 'yield'(
DayCounter& dc,
Compounding comp,
Expand Down
23 changes: 18 additions & 5 deletions quantlib/instruments/bond.pyx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from quantlib.types cimport Real, Size
from quantlib.types cimport Rate, Real, Size
from . cimport _bond
cimport quantlib.time._date as _date

Expand Down Expand Up @@ -75,10 +75,23 @@ cdef class Bond(Instrument):
""" Returns the bond settlement date after the given date."""
return date_from_qldate(self.as_ptr().settlementDate(from_date._thisptr))

@property
def clean_price(self):
""" Bond clean price. """
return self.as_ptr().cleanPrice()
def clean_price(self, *args):
cdef:
Rate y
DayCounter dc
Compounding comp
Frequency freq
Date settlement_date = Date()
if len(args) == 0:
return self.as_ptr().cleanPrice()
else:
if len(args) == 4:
y, dc, comp, freq = args
else:
y, dc, comp, freq, settlement_date = args
return self.as_ptr().cleanPrice(
y, deref(dc._thisptr), comp, freq, settlement_date._thisptr
)

@property
def dirty_price(self):
Expand Down
21 changes: 10 additions & 11 deletions quantlib/interest_rate.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the license for more details.

include 'types.pxi'

from quantlib.types cimport Rate, Real, Time
from cython.operator cimport dereference as deref

from quantlib.handle cimport shared_ptr

from quantlib.time.date cimport Date
from quantlib.time.daycounter cimport DayCounter
cimport quantlib.time._daycounter as _daycounter
from quantlib.compounding cimport Compounding
Expand All @@ -25,12 +22,11 @@ cdef class InterestRate:

"""

def __init__(self, double rate, DayCounter dc not None, Compounding compounding,
int frequency):
def __init__(self, Rate rate, DayCounter dc not None, Compounding compounding,
Frequency frequency):

self._thisptr = _ir.InterestRate(
<Rate>rate, deref(dc._thisptr), compounding,
<_ir.Frequency>frequency
rate, deref(dc._thisptr), compounding, frequency
)


Expand Down Expand Up @@ -68,8 +64,11 @@ cdef class InterestRate:
ss << self._thisptr
return ss.str().decode()

def compound_factor(self, Time t):
return self._thisptr.compoundFactor(t)
def compound_factor(self, Date d1, Date d2, Date ref_start=Date(), Date ref_end=Date()):
return self._thisptr.compoundFactor(d1._thisptr, d2._thisptr, ref_start._thisptr, ref_end._thisptr)

def discount_factor(self, Date d1, Date d2, Date ref_start=Date(), Date ref_end=Date()):
return self._thisptr.discountFactor(d1._thisptr, d2._thisptr, ref_start._thisptr, ref_end._thisptr)

def implied_rate(self, Real compound,
DayCounter result_dc not None,
Expand Down
19 changes: 15 additions & 4 deletions quantlib/math/interpolation.pxd
Original file line number Diff line number Diff line change
@@ -1,18 +1,29 @@
cimport cython
from . cimport _interpolations as _intpl

cdef class Interpolation:
pass

@cython.final
cdef class Linear:
cdef class Linear(Interpolation):
cdef _intpl.Linear _thisptr

@cython.final
cdef class LogLinear:
cdef class LogLinear(Interpolation):
cdef _intpl.LogLinear _thisptr

@cython.final
cdef class BackwardFlat:
cdef class BackwardFlat(Interpolation):
cdef _intpl.BackwardFlat _thisptr

@cython.final
cdef class Cubic:
cdef class Cubic(Interpolation):
cdef _intpl.Cubic _thisptr

@cython.final
cdef class Bicubic(Interpolation):
cdef _intpl.Bicubic _thisptr

@cython.final
cdef class Bilinear(Interpolation):
cdef _intpl.Bilinear _thisptr
2 changes: 1 addition & 1 deletion quantlib/mlab/fixed_income.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ def _bndprice(bond_yield, coupon_rate, pricing_date, maturity_date,

bond.set_pricing_engine(engine)

price = bond.clean_price
price = bond.clean_price()
ac = bond.accrued_amount(pydate_to_qldate(settlement_date))

return (price, ac)
Expand Down
11 changes: 11 additions & 0 deletions quantlib/pricingengines/bond/_bondfunctions.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,17 @@ cdef extern from 'ql/pricingengines/bond/bondfunctions.hpp' namespace 'QuantLib:
cdef Date startDate(Bond bond)
cdef Leg.const_reverse_iterator previousCashFlow(const Bond& bond,
Date refDate) # = Date()
cdef Leg.const_iterator nextCashFlow(const Bond& bond,
Date refDate) # = Date()

cdef Date previousCashFlowDate(const Bond& bond,
Date refDate)
cdef Date nextCashFlowDate(const Bond& bond,
Date refDate)
cdef Real previousCashFlowAmount(const Bond& bond,
Date refDate)
cdef Real nextCashFlowAmount(const Bond& bond,
Date refDate)
cdef Time duration(Bond bond,
Rate yld,
DayCounter dayCounter,
Expand Down
28 changes: 26 additions & 2 deletions quantlib/pricingengines/bond/bondfunctions.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,37 @@ def start_date(Bond bond):
return date_from_qldate(_bf.startDate(deref(bond.as_ptr())))

def previous_cash_flow(Bond bond, Date ref_date=Date()):
cdef Leg.const_reverse_iterator it = _bf.previousCashFlow(deref(bond.as_ptr()), ref_date._thisptr)
cdef Leg.const_reverse_iterator it = _bf.previousCashFlow(deref(bond.as_ptr()), ref_date._thisptr)
cdef CashFlow cf = CashFlow.__new__(CashFlow)
while it != bond.as_ptr().cashflows().const_rbegin():
while it != bond.as_ptr().cashflows().const_rend():
cf._thisptr = deref(it)
yield cf
preinc(it)

def next_cash_flow(Bond bond, Date ref_date=Date()):
cdef Leg.const_iterator it = _bf.nextCashFlow(deref(bond.as_ptr()), ref_date._thisptr)
cdef CashFlow cf = CashFlow.__new__(CashFlow)
while it != bond.as_ptr().cashflows().const_end():
cf._thisptr = deref(it)
yield cf
preinc(it)


def previous_cash_flow_date(Bond bond, Date ref_date=Date()):
cdef Date d = Date.__new__(Date)
d._thisptr = _bf.previousCashFlowDate(deref(bond.as_ptr()), ref_date._thisptr)
return d

def next_cash_flow_date(Bond bond, Date ref_date=Date()):
cdef Date d = Date.__new__(Date)
d._thisptr = _bf.nextCashFlowDate(deref(bond.as_ptr()), ref_date._thisptr)
return d

def previous_cash_flow_amount(Bond bond, Date ref_date=Date()):
return _bf.previousCashFlowAmount(deref(bond.as_ptr()), ref_date._thisptr)

def next_cash_flow_amount(Bond bond, Date ref_date=Date()):
return _bf.nextCashFlowAmount(deref(bond.as_ptr()), ref_date._thisptr)

def duration(Bond bond not None,
Rate yld,
Expand Down
14 changes: 14 additions & 0 deletions quantlib/termstructures/default_term_structure.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -47,3 +47,17 @@ cdef class HandleDefaultProbabilityTermStructure:
self.handle = RelinkableHandle[_dts.DefaultProbabilityTermStructure](
static_pointer_cast[_dts.DefaultProbabilityTermStructure](ts._thisptr),
register_as_observer)

@property
def current_link(self):
cdef DefaultProbabilityTermStructure instance = DefaultProbabilityTermStructure.__new__(DefaultProbabilityTermStructure)
if self.handle.empty():
raise ValueError("empty handle")
instance._thisptr = self.handle.currentLink()
return instance

def link_to(self, DefaultProbabilityTermStructure ts, bool register_as_observer=True):
self.handle.linkTo(
static_pointer_cast[_dts.DefaultProbabilityTermStructure](ts._thisptr),
register_as_observer
)
1 change: 1 addition & 0 deletions quantlib/termstructures/vol_term_structure.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ from . cimport _vol_term_structure as _vts
cdef class VolatilityTermStructure:
cdef shared_ptr[_vts.VolatilityTermStructure] _thisptr
cdef _vts.VolatilityTermStructure* as_ptr(self) nogil

@staticmethod
cdef Handle[_vts.VolatilityTermStructure] handle(object vol)

Expand Down
2 changes: 1 addition & 1 deletion quantlib/termstructures/vol_term_structure.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ cdef class VolatilityTermStructure:
elif isinstance(vol, HandleVolatilityTermStructure):
return (<HandleVolatilityTermStructure>vol).handle
else:
raise TypeError("vol needs to be either a SwaptionVolatilityStructure or a HandleSwaptionVolatilityStructure")
raise TypeError("vol needs to be either a VolatilityTermStructure or a HandleVolatilityTermStructure")

def time_from_reference(self, Date date not None):
return self.as_ptr().timeFromReference(date._thisptr)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,5 @@ cdef extern from 'ql/termstructures/volatility/equityfx/blackvariancesurface.hpp
ConstantExtrapolation
InterpolatorDefaultExtrapolation

cpdef enum Interpolator:
Bilinear
Bicubic

cdef class BlackVarianceSurface(BlackVarianceTermStructure):
pass
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ from libcpp.vector cimport vector

from quantlib.handle cimport shared_ptr
from quantlib.math.matrix cimport Matrix
cimport quantlib.math._interpolations as intpl
from quantlib.math.interpolation cimport Interpolation, Bilinear, Bicubic

from quantlib.time.date cimport Date, date_from_qldate
from quantlib.time._date cimport Date as _Date
from quantlib.time.calendar cimport Calendar
Expand Down Expand Up @@ -89,10 +90,10 @@ cdef class BlackVarianceSurface(BlackVarianceTermStructure):
return get_bvs(self).maxStrike()

# Modifiers
def set_interpolation(self, Interpolator i):
if i == Bilinear:
get_bvs(self).setInterpolation[intpl.Bilinear]() # Calls the default constructor
elif i == Bicubic:
get_bvs(self).setInterpolation[intpl.Bicubic]()
def set_interpolation(self, Interpolation i):
if isinstance(i, Bicubic):
get_bvs(self).setInterpolation((<Bicubic>i)._thisptr) # Calls the default constructor
elif isinstance(i, Bilinear):
get_bvs(self).setInterpolation((<Bilinear>i)._thisptr)
else:
raise ValueError("Interpolator must be Bilinear or Bicubic")
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from cython.operator cimport dereference as deref
from libcpp.vector cimport vector
from quantlib.compounding cimport Compounding, Continuous
from quantlib.compounding cimport Compounding
from quantlib.handle cimport Handle
from quantlib.time.daycounter cimport DayCounter
from quantlib.time.frequency cimport Frequency, NoFrequency
Expand All @@ -13,7 +13,7 @@ from . cimport _piecewise_zerospreaded_termstructure as _pzt

cdef class PiecewiseZeroSpreadedTermStructure(YieldTermStructure):
def __init__(self, HandleYieldTermStructure h not None, list spreads, list dates,
Compounding comp=Continuous, Frequency freq=NoFrequency,
Compounding comp=Compounding.Continuous, Frequency freq=NoFrequency,
DayCounter dc not None=DayCounter()):
cdef vector[Handle[_qt.Quote]] spreads_vec
cdef vector[QlDate] dates_vec
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from cython.operator cimport dereference as deref
from quantlib.compounding cimport Compounding, Continuous
from quantlib.compounding cimport Compounding
from quantlib.termstructures.yield_term_structure cimport HandleYieldTermStructure
from quantlib.time.daycounter cimport DayCounter
from quantlib.time.frequency cimport Frequency, NoFrequency
Expand All @@ -8,7 +8,7 @@ from . cimport _zero_spreaded_term_structure as _zsts

cdef class ZeroSpreadedTermStructure(YieldTermStructure):
def __init__(self, HandleYieldTermStructure h not None, Quote spread,
Compounding comp=Continuous, Frequency freq=NoFrequency,
Compounding comp=Compounding.Continuous, Frequency freq=NoFrequency,
DayCounter dc not None=DayCounter()):

self._thisptr.reset(
Expand Down
12 changes: 6 additions & 6 deletions quantlib/time/_period.pxd
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ from libcpp.string cimport string

from .frequency cimport Frequency

cdef extern from 'ql/time/timeunit.hpp' namespace "QuantLib":
cdef extern from 'ql/time/timeunit.hpp' namespace "QuantLib" nogil:
cdef enum TimeUnit:
Days
Weeks
Expand All @@ -16,7 +16,7 @@ cdef extern from 'ql/time/timeunit.hpp' namespace "QuantLib":
Milliseconds
Microseconds

cdef extern from 'ql/time/period.hpp' namespace "QuantLib":
cdef extern from 'ql/time/period.hpp' namespace "QuantLib" nogil:

cdef cppclass Period:

Expand Down Expand Up @@ -52,20 +52,20 @@ cdef extern from 'ql/time/period.hpp' namespace "QuantLib":
Real weeks(const Period& p) except +
Real days(const Period& p) except +

cdef extern from 'ql/utilities/dataparsers.hpp' namespace "QuantLib::PeriodParser":
cdef extern from 'ql/utilities/dataparsers.hpp' namespace "QuantLib::PeriodParser" nogil:
Period parse(string& str) except +

cdef extern from "ql/time/period.hpp" namespace "QuantLib::detail":
cdef extern from "ql/time/period.hpp" namespace "QuantLib::detail" nogil:
cdef cppclass long_period_holder:
pass
cdef cppclass short_period_holder:
pass

cdef extern from "ql/time/period.hpp" namespace "QuantLib::io":
cdef extern from "ql/time/period.hpp" namespace "QuantLib::io" nogil:
cdef short_period_holder short_period(const Period&)
cdef long_period_holder long_period(const Period&)

cdef extern from "<sstream>" namespace "std":
cdef extern from "<sstream>" namespace "std" nogil:
cdef cppclass stringstream:
stringstream& operator<<(long_period_holder)
stringstream& operator<<(short_period_holder)
Expand Down
Loading
Loading