Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Quantlib convert Quantlib Date to datetime

I have a list of dates defined in the Date format of quantlib. How can I convert these into datetime format. The reason I am asking is, that I would like to plot it and I received the follwoing error:

TypeError: float() argument must be a string or a number, not 'Date'

when doing the following:

plt.plot(dates,rates, linewidth=2.0) # Without date plotting works out.

dates looks like the following:

[
  Date(11,12,2012), 
  Date(12,12,2012), 
  Date(13,12,2012),
  Date(14,12,2012), 
  Date(15,12,2012), 
  Date(16,12,2012),
  Date(17,12,2012), 
  Date(18,12,2012), 
  Date(19,12,2012),
  Date(20,12,2012)
]
like image 790
MCM Avatar asked Dec 24 '22 16:12

MCM


1 Answers

There's no predefined conversion, so you'll have to extract the information from the QuantLib date and use it to build a datetime instance. E.g., define something like

def ql_to_datetime(d):
    return datetime.datetime(d.year(), d.month(), d.dayOfMonth())

after which you can use ql_to_datetime(d) for a single date, or [ ql_to_datetime(d) for d in dates ] for a list. (You can also define another function taking a list, of course.)

Update: in recent versions of QuantLib-Python, a predefined conversion was added. You can now say d.to_date() to convert a date, or [d.to_date() for d in dates] for a list.

like image 147
Luigi Ballabio Avatar answered Jan 12 '23 08:01

Luigi Ballabio